请注意,如the docs http://docs.python.org/2/library/csv.html say:
csvfile可以是任何支持迭代器协议并每次返回一个字符串的对象next()
方法被调用——文件对象和列表对象都适合。
因此,您始终可以在将文件交给您之前对其进行过滤reader
or DictReader
。而不是这个:
with open('myfile.csv', 'rU') as myfile:
for row in csv.reader(myfile):
Do this:
with open('myfile.csv', 'rU') as myfile:
filtered = (line.replace('\r', '') for line in myfile)
for row in csv.reader(filtered):
That '\r'
是 Python(和 C)的拼写方式^M
。所以,这只是剥夺了所有^M
字符,无论它们出现在哪里,通过用空字符串替换每个字符。
我想我想永久修改该文件而不是过滤它。
首先,如果您想在运行 Python 脚本之前修改该文件,为什么不从 Python 外部执行此操作呢?sed
, tr
、许多文本编辑器等都可以为您完成此操作。这是一个 GNU sed 示例:
gsed -i'' 's/\r//g' myfile.csv
但如果你想用 Python 来做,它并没有那么冗长,你可能会发现它更具可读性,所以:
首先,如果您想从中间插入或删除文件,则无法真正就地修改文件。通常的解决方案是写入一个新文件,然后将新文件移动到旧文件上(仅限 Unix)或删除旧文件(跨平台)。
跨平台版本:
os.rename('myfile.csv', 'myfile.csv.bak')
with open('myfile.csv.bak', 'rU') as infile, open('myfile.csv', 'wU') as outfile:
for line in infile:
outfile.write(line.replace('\r'))
os.remove('myfile.csv.bak')
不太笨重但仅限 Unix 的版本:
temp = tempfile.NamedTemporaryFile(delete=False)
with open('myfile.csv', 'rU') as myfile, closing(temp):
for line in myfile:
temp.write(line.replace('\r'))
os.rename(tempfile.name, 'myfile.csv')