CSV Reader在Ubuntu和Windows上的不同输出-Python [英] CSV Reader different outputs on Ubuntu and Windows - Python
问题描述
我有一个名为Some.csv的文件,该文件的字段(列)的值类似于
1000,2000,.... 39000.
我只想要39000的文件,所以我写了下面的python脚本
import os导入csv使用open('Somenew.csv','w')作为fw:writr = csv.writer(fw,delimiter =',')将open('Some.csv','r')设为fr:reader = csv.reader(fr,分隔符=',')对于阅读器中的行:如果row [2] =='39000':writr.writerow(row)
现在,当它在Windows上执行时,Somenew.csv看起来像这样
xxxx,xxxx,39000,xxxx,xxxx
yyyy,yyyy,39000,yyyy,yyyy
但是在Linux(Ubuntu 14.04LTS)上执行时,没有添加额外的换行符.
这有什么原因吗?也许是因为编译器造成的?
如果使用的是Python 2.x,则必须对 csv
文件使用 wb
模式:>
https://docs.python.org/2/library/csv.html#csv.writer
如果csvfile是文件对象,则必须在有区别的平台上使用"b"标志打开它.
I have a file called Some.csv which has a field (column) which has values like
1000, 2000, .... 39000.
I wanted only the files with 39000 so I wrote the following python script
import os
import csv
with open('Somenew.csv', 'w') as fw:
writr = csv.writer(fw, delimiter=',')
with open('Some.csv','r') as fr:
reader = csv.reader(fr, delimiter = ',')
for row in reader:
if row[2] == '39000': writr.writerow(row)
Now when this executes on Windows it Somenew.csv looks like this
xxxx, xxxx, 39000, xxxx, xxxx
yyyy, yyyy, 39000, yyyy, yyyy
But when executing on Linux (Ubuntu 14.04LTS) there is no extra newline added.
Is there any reason for this? Is it perhaps because of the compiler?
You must use wb
mode for csv
files if you are using Python 2.x:
https://docs.python.org/2/library/csv.html#csv.writer
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
这篇关于CSV Reader在Ubuntu和Windows上的不同输出-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!