20

I want to end each interation of a for loop with writing a new line of content (including newline) to a csv file. I have this:

# Set up an output csv file with column headers
with open('outfile.csv','w') as f:
    f.write("title; post")
    f.write("\n")

This does not appear to write an actual \n (newline) the file. Further:

    # Concatenate into a row to write to the output csv file
    csv_line = topic_title + ";" + thread_post
    with open('outfile.csv','w') as outfile:
                 outfile.write(csv_line + "\n")

This, also, does not move the cursor in the outfile to the next line. Each new line, with every iteration of the loop, just overwrites the most recent one.

I also tried outfile.write(os.linesep) but did not work.

Simon Lindgren
  • 2,011
  • 12
  • 32
  • 46

5 Answers5

20

change 'w' to 'a'

with open('outfile.csv','a')
fuwiak
  • 721
  • 1
  • 8
  • 25
  • 2
    Why would this work ? Can you explain how changing the access modifier alters the EOL character? Why wouldn't write('\n') work ? – Sean Munson Aug 19 '19 at 18:15
  • 1
    I think OP is opening/closing the file within a loop (they mention a loop but don't show where it is), so opening in append mode is a "fix", but is *the wrong way*. – Nick T Jan 03 '20 at 21:15
  • Yes, that's a workaround, not a solution. – sjantke Jan 25 '21 at 14:11
5
with open('outfile.csv', 'w', newline='') as f:
    f.writerow(...)

Alternatively:

f = csv.writer('outfile.csv', lineterminator='\n')
Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
1

I confront with same problem, only need follow:

  f = csv.writer('outfile.csv', lineterminator='\n')
Lee Ran
  • 11
  • 4
1

If your using python2 then use

with open('xxx.csv', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(fields)

If you are using python3 make use of newline=''

crodev
  • 1,323
  • 6
  • 22
  • 39
Prashant
  • 11
  • 1
0

Please try with: open(output_file_name.csv, 'a+', newline='') as f:

Toto Briac
  • 908
  • 9
  • 29
e.amin
  • 1