Python CSV reads file and selects columns and writes to new CSV file

I have a CSV file that has specific columns that I need to extract. One of these columns is a text string from which I need to extract the first and last elements. I have a print statement in a for loop that gets exactly what I need, but cannot figure out how to get this data in a list or dict. Not sure which is 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() 

File entry:

 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, 

Print output:

 SUPPORT Test Company 2015-05-29 14:32:26 IS 
+5
source share
2 answers

With some testing, I finally get a line to write the csv file:

 for row in reader: writer.writerow([row['User Name'],row['Address'].split(',')[0],row['Last Login DateTime'],row['Address'].split(',')[7]]) 
0
source

Using this code, I have the required line:

 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:

  • Enabling import csv at the top.
  • Indentation of the code immediately after with open('out.csv' ......

Does this solve your problem?

0
source

All Articles