Building list of lists from CSV file

前端 未结 3 866
不思量自难忘°
不思量自难忘° 2021-01-11 13:42

I have an Excel file(that I am exporting as a csv) that I want to parse, but I am having trouble with finding the best way to do it. The csv is a list of computers in my net

3条回答
  •  [愿得一人]
    2021-01-11 14:21

    This should get you on the right track:

    import csv 
    import sys #used for passing in the argument
    file_name = sys.argv[1] #filename is argument 1
    with open(file_name, 'rU') as f:  #opens PW file
        reader = csv.reader(f)
        data = list(list(rec) for rec in csv.reader(f, delimiter=',')) #reads csv into a list of lists
    
        for row in data:
            print row[0] #this alone will print all the computer names
            for username in row: #Trying to run another for loop to print the usernames
                print username
    

    Last two lines will print all of the row (including the "computer"). Do

    for x in range(1, len(row)):
        print row[x]
    

    ... to avoid printing the computer twice.

    Note that f.close() is not required when using the "with" construct because the resource will automatically be closed when the "with" block is exited.

    Personally, I would just do:

    import csv 
    import sys #used for passing in the argument
    file_name = sys.argv[1] #filename is argument 1
    with open(file_name, 'rU') as f:  #opens PW file
        reader = csv.reader(f)
        # Print every value of every row. 
        for row in reader:
            for value in row: 
                print value
    

    That's a reasonable way to iterate through the data and should give you a firm basis to add whatever further logic is required.

提交回复
热议问题