Same code producing distinct results in Codeenvy and Windows 8.1

0

I had made the following code in codevy.io and the Python installed in codenvy is 3.5.1. I got this code and put it to run on windows 8 with python 3.6.1.

The purpose of the code is to clean up a CSV file and write them concatenated in a single CSV file. In codenvy it's working, but when I run the code in windows the output file gets blank lines between each row, I want to know how to get around this:

import csv
import sys
import os
import glob

interesting_files = glob.glob("Vendas_artigos*")

with open('SaidaVendasArtigos.csv','wt',encoding='utf-8-sig') as fout:
    for filename in sorted(interesting_files):
        with open(filename,'rt',encoding='utf-8-sig') as fin:
            next(fin)
            reader = csv.reader(fin)
            writer = csv.writer(fout)
            for row in reader:
                if row:
                    row.pop(0)
                writer.writerow(row)

Python 3.5.1 on Codenvy:

row
row
row

Python 3.6.1 on Windows 8:

row

row

row
    
asked by anonymous 05.05.2017 / 16:52

1 answer

1

I may be wrong, but it may be that at the moment you use writerow the variable row already has line break, so you could use .strip like this:

reader = csv.reader(fin)
writer = csv.writer(fout)
for row in reader:
    if row:
        row.pop(0)
    writer.writerow(row.strip('\r\n'))

In the argument of strip , I used \r and \n to remove only line breaks (LF) and carriage return (CR)

Something that made me curious was the use of row.pop(0) , I think this will always remove the first item from the index, affecting the behavior of for which seems like it can cause a lot of confusion in for myself even I did not understand the need to manipulate the vector if you were just copying the data to a new file, I think maybe you wanted to do something like this:

for row in reader:
    if row:
        writer.writerow(row)

Or:

for row in reader:
    if row:
        writer.writerow(row.strip('\r\n'))

And reader if you really want to "manipulate" for later use, you could manipulate with pop before or after in for

    
05.05.2017 / 17:49