Python CSV读取文件并选择列并写入新的CSV文件

时间:2015-06-19 13:00:34

标签: python csv

我有一个CSV文件,其中包含我需要提取的某些列。其中一列是一个文本字符串,我需要从中提取第一个和最后一个项目。我在for循环中有一个print语句,它正是我所需要的,但却无法弄清楚如何将这些数据放入列表或dict中。不确定哪个是最好用的。

到目前为止

代码:

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

从文件输入:

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,

打印输出:

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

2 个答案:

答案 0 :(得分:0)

使用此代码,我得到了您需要的行:

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

唯一的变化:

  • 在顶部包含import csv
  • with open('out.csv' ......
  • 之后缩进代码

这会解决您的问题吗?

答案 1 :(得分:0)

With some testing I finally get the 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]])