【发布时间】:2017-12-22 21:46:25
【问题描述】:
考虑以下 CSV:
"""tom"""
""fred""
"henry"
Jack
"""mary"""
下面会查找我定义的一些字符,删除它们,然后在每行(行)的末尾添加一个字符串。它“有效”,但我不确定我是否以正确的方式进行......在我看来,应该打开、编辑和保存原始文件。我将针对数千个 CSV 文件运行它,因此它会变得非常混乱。
import csv
s = open('Book1.csv','r').read()
chars = ('$','%','^','*','"','_') # etc
for c in chars:
s = ''.join( s.split(c) )
out_file = open('Book2.csv','w')
out_file.write(s)
out_file.close()
output = ""
file_name = 'Book2.csv'
string_to_add = "@bigfoot.com"
with open(file_name, 'r') as f:
file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()]
with open(file_name, 'w') as f:
f.writelines(file_lines)
tom@bigfoot.com
fred@bigfoot.com
henry@bigfoot.com
Jack@bigfoot.com
mary@bigfoot.com
【问题讨论】:
-
它不是真正的 csv / 至少根本不使用
csv模块,而是使用文本处理。字符可以在字符串的中间吗? -
为什么不读取文件行,执行替换+添加然后写回原始文件?
-
no 字符将始终位于原始字符串的任一端,删除字符后要添加的字符串将始终附加到末尾
标签: python python-3.x python-2.7 csv