CSV Reader different outputs on Ubuntu and Windows - Python [duplicate]

孤者浪人 提交于 2021-02-11 12:36:12

问题


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?


回答1:


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.




回答2:


Try to open your file in binary mode. This answer may help.



来源:https://stackoverflow.com/questions/36494688/csv-reader-different-outputs-on-ubuntu-and-windows-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!