0

I see some unsolved related questions, so... here I am to toss a coin and see if anyone can help me!

I´m using the CSV module to create csv files, but for each created line, the code adds one blank line.

The csv module has 2 ways to write a csv file: list mode and ordered dict mode. Both create the same problem.

I pasted here a "list mode" code.

from csv import writer
 
with open('movies.csv', 'w') as file:
    writer_csv = writer(file)
    movie = None
    writer_csv.writerow(['Title', 'Genre', 'Lenght'])
    while movie != 'finish':
        movie = input('Movie name: ')
        if movie != 'finish':
            genre = input('Genre: ')
            lenght = input('Lenght: ')
            writer_csv.writerow([movie, genre, lenght])

Everything works fine, but the extra blank line.

The result is...

Title,Genre,Lenght

Bourne Identity,Action,120

Bourne Supremacy,Action,125

Ultimatum Bourne,Action,128

And the desired result is...

Title,Genre,Lenght
Bourne Identity,Action,120
Bourne Supremacy,Action,125
Ultimatum Bourne,Action,128

Thank's for any help!

  • This solved the undesired line break: `with open('movies.csv', 'w', newline='') as file:` (found [here](https://stackoverflow.com/questions/3191528/csv-in-python-adding-an-extra-carriage-return-on-windows)) – DeusDev Jul 14 '21 at 03:45
  • I don't see extra blank lines in the file when I run this code. Are you running on Windows? And how are you opening the file to see the extra blank lines? – John Gordon Jul 14 '21 at 03:54
  • _Every single example_ in the csv documentation opens the file using something like this: `with open('eggs.csv', newline='') as csvfile:` - the `newline=‘’` isn’t there for no reason. Read the documentation https://docs.python.org/3/library/csv.html?highlight=csv#module-csv – DisappointedByUnaccountableMod Jul 14 '21 at 06:25
  • Thank you my friends, great help! Yes John, the problem is the windows, which affects somehow the whole lib CSV. Hope Windows 11 comes for good! – TamerSalmem Jul 14 '21 at 21:46

1 Answers1

0

You need to specify a newline -

with open('movies.csv', 'w',newline='') as file:

By default, newline is '\n'

PCM
  • 2,881
  • 2
  • 8
  • 30