-5

when i use the write mode:

d = open("test.txt","a")
d.write(letter)

it always appends the text at the end everytime i write someting into the file. My question is, how to write as new line like this:

a
b
c

Currently it writes:

abc

Using \n does not work unfortunally...

Thanks so much

ddd
  • 167
  • 1
  • 7
  • 3
    What code do you have already that writes to the file object `d`? – Adam Jan 03 '19 at 22:44
  • 4
    `/n` is not `\n`. – user2357112 Jan 03 '19 at 22:45
  • i just edited the code – ddd Jan 03 '19 at 22:47
  • ...and how are you creating the variable `letter`? – Adam Jan 03 '19 at 22:48
  • So... are you using `\n` or `/n`? – Ender Look Jan 03 '19 at 22:50
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. – Prune Jan 03 '19 at 22:51

3 Answers3

2

You can either add a newline character after the letter:

d.write(letter + '\n')

Or if you are using Python 3 or if you from __future__ import print_function in Python 2:

print(letter, file=d)
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

As mentioned here, you can do :

with open('test.txt', 'a') as d:

    d.write('YOURTEXT\n')
0

The new-line character "\n" works fine with "a" (append) option for writing files in python.

Example:

d = open(filepath, "a")
d.write("hello")
d.write("\n")
d.write("hello again")
d.close()

o/p:

hello
hello again

OR -> To append text from next line of the existing text of file.

d.write('\n')
d.write("hello" + '\n')