我有一个CSV文件,如下所示:
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_02,983,0,Prod,983
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_03,124,0,Prod ,124
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_04,206,0,Prod,206
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_05,983,0,Prod ,983
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_06,564,0,Prod,564
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_07,189,0,Prod ,189
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_08,168,0,Prod,168
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_09,570,0,Prod ,570
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_10,189,0,Prod,189
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_11,204,0,Prod ,204
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_12,189,2,Prod,187
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_13,568,0,Prod ,568
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_14,204,0,Prod,204
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_15,142,0,Prod ,142
File,2/13/2017,domain\test_roi,root_user,ntsrv1,/vol/vol_ntsrv1_16,168,0,Prod,168
我想在列表中添加第4列(root_user)和第7列(编写数字的列表)。有什么建议吗?
答案 0 :(得分:0)
这种方式非常简单:
fourth_column_list = []
seventh_column_list = []
with open(my_csv_file, 'r') as infile:
parsed = (x.split(',') for line in infile) # get all parsed columns
for parsed_line in parsed: # iterate over parsed lines
fourth_column_list.append(parsed_line[3]) # append 4th column
seventhth_column_list.append(parsed_line[6]) # append 7th column
答案 1 :(得分:0)
import csv
four_col, seven_col = [], []
with open(file='test.csv', mode='r', encoding='utf-8') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
# firstline = csvfile.readline() # if csv have header uncomment it
for row in spamreader:
four_col.append(row[3])
seven_col.append(row[6])
使用此csv文件,您可以将其设置为将spamreader设置为:
spamreader = csv.reader(csvfile, dialect='excel')
但如果文件不使用逗号分隔符,我写了更通用的方法。