简体   繁体   English

要在python中列出的csv文件

[英]csv file to list in python

I have a CSV file which looks like this:我有一个 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

I want to add to a list the 4th column (root_user) and the 7th column (where the numbers are written).我想将第 4 列 (root_user) 和第 7 列(写入数字的位置)添加到列表中。 Any suggestions how?任何建议如何?

It's pretty simple this way:这种方式非常简单:

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
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])

With this csv file you can read it also setting the spamreader as:使用此 csv 文件,您还可以将 spamreader 设置为:

spamreader = csv.reader(csvfile, dialect='excel')

but I wrote you the more generic way if the file don't uses commas for delimiter.但如果文件不使用逗号作为分隔符,我会以更通用的方式给您写信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM