0

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?

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
Sood
  • 149
  • 1
  • 1
  • 11
  • It's because Windows uses `\r\n` for line endings in text files instead of `\n`. The simple fix is to read & write your CSV files as binary files, but there are other options in Python 3. What version of Python are you using? – PM 2Ring Apr 08 '16 at 08:19
  • 2
    http://stackoverflow.com/questions/1170214/pythons-csv-writer-produces-wrong-line-terminator/1170297#1170297 – LearnerEarner Apr 08 '16 at 08:21
  • 2.7.something (probably 10). Thanks that makes sense. So change 'r' and 'w' to 'rb' and 'wb'? – Sood Apr 08 '16 at 08:21

2 Answers2

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.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
0

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

Community
  • 1
  • 1