Python CSV read file and select columns and write to new CSV file
Question: I have a CSV file which has certain columns which I need to extract. One of
those columns is a text string from which I need to extract the first and last
items. I have a print statement in a for loop which get exactly what I need
but cannot figure out how to either get that data into a list or dict. Not
sure which is the best to use.

Code so far:

    
    
    f1 = open ("report.csv","r") # open input file for reading 
    users_dict = {}
    with open('out.csv', 'wb') as f: # output csv file
    
    writer = csv.writer(f)
    with open('report.csv','r') as csvfile: # input csv file
        reader = csv.DictReader(csvfile, delimiter=',')
        for row in reader:
            print row['User Name'],row['Address'].split(',')[0],row['Last Login DateTime'],row['Address'].split(',')[7]
            users_dict.update(row)
            #users_list.append(row['Address'].split(','))
            #users_list.append(row['Last Login DateTime'])
            #users_list.append(row[5].split(',')[7])
    
    print users_dict
    
    f1.close() 
    

Input from file:

    
    
    User Name,Display Name,Login Name,Role,Last Login DateTime,Address,Application,AAA,Exchange,Comment
    SUPPORT,SUPPORT,SUPPORT,124,2015-05-29 14:32:26,"Test Company,Bond St,London,London,1111 111,GB,test@test.com,IS",,,LSE,
    

Output on print:

    
    
    SUPPORT Test Company 2015-05-29 14:32:26 IS
    


Answer: Using this code, I've got the line you need:

    
    
    import csv
    f1 = open ("report.csv","r") # open input file for reading 
    users_dict = {}
    with open('out.csv', 'wb') as f: # output csv file
        writer = csv.writer(f)
        with open('report.csv','r') as csvfile: # input csv file
            reader = csv.DictReader(csvfile, delimiter=',')
            for row in reader:
                print row['User Name'],row['Address'].split(',')[0],row['Last Login DateTime'],row['Address'].split(',')[7]
                users_dict.update(row)
                #users_list.append(row['Address'].split(','))
                #users_list.append(row['Last Login DateTime'])
                #users_list.append(row[5].split(',')[7])
    
        print users_dict
    
    f1.close()
    

The only changes:

  * Including the `import csv` at the top.
  * Indenting the code just after the `with open('out.csv' ......`

Does this solve your problem?

