使用python替换csv文件中的数据

2024-04-23 07:38:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是新的输入文件格式。我需要自动化使用python替换.csv文件中一列内容的过程。我也可以使用记事本打开.csv文件并替换列的内容,但该文件非常大,需要很长时间。

Name                          ID                                                class  Num
"kanika",""University ISD_po.log";" University     /projects/asd/new/high/sde"","MBA","12"
"Ambika",""University ISD_po.log";" University     /projects/asd/new/high/sde"","MS","13"

在上面,我需要替换ID列的内容。ID列非常不一致,因为它在内容中有很大的空格和(;,/)等符号。ID列中的新内容应该是“input”。

这个Id列用两个双引号括起来,还有一些额外的空格。而其他列只有一个双引号。

用python有什么办法吗?


Tags: 文件csvlogid内容newpoprojects
2条回答

您可以使用Python中的csv模块来实现这一点。

reader将以字符串列表的形式返回每一行。然后,可以使用csv.writer对每一行进行流式处理,并在此时修改ID列,这将创建一个新文件。

所以:

import csv
reader = csv.reader(open('file.csv', 'rb'))
writer = csv.writer(open('outfile.csv','wb'))
for row in reader:
    writer.writerow([row[0], "input", row[2], row[3]])

逐行读取.csv,在,上拆分,并用“input”替换第二列。 一边写(到另一个文件中):

f = open('mycsv.csv','rb')
fo = open('out.csv','wb')

# go through each line of the file
for line in f:
    bits = line.split(',')
    # change second column
    bits[1] = '"input"'
    # join it back together and write it out
    fo.write( ','.join(bits) )

f.close()
fo.close()

如果愿意,可以重命名它以替换原始文件。

相关问题 更多 >