SnappyPenguin
SnappyPenguin

Reputation: 97

Appending variable to end of file on a newline in Python

I am trying to append the data from a variable to the end of a file Python - on a new line. I have used this method: (variable+"/n") but in the file it has all of the file data on one line including the /n symbol.

My code (this is an example! So it makes sense in exactly what I want to be answered):

list = ["apple","pear","strawberry"]
f = open("test.txt","a")
for x in list:
    f.write(x+"/n")
    print(x)
f.close()

Output in test.txt:

apple/npear/nstrawberry/n

What can I do so that the output looks like this:

apple
pear
strawberry

Thank you in advance for your answers!

Upvotes: 0

Views: 169

Answers (3)

Mike
Mike

Reputation: 11

Try using \n instead of /n on line 5.

Upvotes: 1

Dejene T.
Dejene T.

Reputation: 989

The following code works correctly

list = ["apple","pear","strawberry"]
    f = open("test.txt","a")
    for x in list:
      f.write(x)
      print(x, end='/n')
    f.close()

Output:

apple/npear/nstrawberry/n

Upvotes: 0

Arpit Omprakash
Arpit Omprakash

Reputation: 118

Replace forward-slash (/) with a backslash ().

Code:

list = ["apple","pear","strawberry"]
f = open("test.txt","a")
for x in list:
    f.write(x+"\n")
    print(x)
f.close()

Upvotes: 1

Related Questions