A coding skrub
A coding skrub

Reputation: 11

Adding a paragraph in a file from python

I am appending a file via python based on the code that has been input by the user.

with open ("markbook.txt", "a") as g:
        g.write(sn+","+sna+","+sg1+","+sg2+","+sg3+","+sg4)

sn, sna, sg1, sg2, sg3, sg4 have all been entered by the user and when the program is finished a line will be added to the 'markbook.txt' file in the format of:

00,SmithJE,a,b,b,b
01,JonesFJ,e,d,c,d
02,BlairJA,c,c,b,a
03,BirchFA,a,a,b,c

The issue is when the program is used again and the file is appended further, the new line is simply put on the end of the previous line. How do I place the appended text below the previous line?

Upvotes: 1

Views: 1601

Answers (3)

Jamie Finnigan
Jamie Finnigan

Reputation: 21

You're missing the new line character at the end of your string. Also, though string concatenation is completely fine in this case, you should be aware that Python has alternative options for formatting strings.

    with open('markbook.txt', 'a') as g:
        g.write('{},{},{},{},{},{}\n'
               .format(sn, sna, sg1, sg2, sg3, sg4))

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122132

You need to write line separators between your your lines:

g.write(sn + "," + sna + "," + sg1 + "," + sg2 + "," + sg3 + "," + sg4 + '\n')

You appear to be reinventing the CSV wheel, however. Leave separators (line or column) to the csv library instead:

import csv

with open ("markbook.txt", "ab") as g:
    writer = csv.writer(g)
    writer.writerow([sn, sna, sg1, sg2, sg3, sg4])

Upvotes: 1

MasterOdin
MasterOdin

Reputation: 7886

Add a "\n" to the end of the write line.

So:

g.write(sn+","+sna+","+sg1+","+sg2+","+sg3+","+sg4+"\n")

Upvotes: 1

Related Questions