Ok so for the last couple of days I have been struggling with file handling. Here is my problem I create a new file and write some text into it. Then I open it again to add more text to it but somehow the new text is being written in the same line as the previous text without leaving space between each other.

here is my code:

test =open("Hello World.txt", "w")
test.write("Hello World!")
test.close()
test = open("Hello World.txt", "r")
test.read()
'Hello World!'
test.close()
test = open("Hello World.txt", "a")
test.write("hello world!")
test.close()
test = open("Hello World.txt", "r")
test.read()
'Hello World!hello world!'

As you can see after I appended more text into the file i ended up with 'Hello World!hello world!', when I wanted to get them spaced out. Any solutions?

Recommended Answers

All 4 Replies

file.write() methods write unformatted characters to the file.
That is, it do not work like a print statement.
When you issue a print statement, a new line is automatically appended. This is not the case with write().
write() performs as-is writing.

You could redirect your stdout to a file and then use the normal print statement to print formated text. http://stefaanlippens.net/redirect_python_print
Else, you could just add a space before writing to the file:

test = open("Hello World.txt", "a")
test.write(" hello world!")

Well is there a way to get what I append to a file in a new line.

So that the output would be:

'Hello World'
'hello world'
# instead of
'Hello World!hello world!'

You can simply modify your code a little ...

test = open("Hello_World.txt", "w")
test.write("Hello World!")
test.close()

test = open("Hello_World.txt", "r")
print test.read()
test.close()

print '-'*20

test = open("Hello_World.txt", "a")
# add the newline char in front
test.write("\nhello world!")
test.close()

test = open("Hello World.txt", "r")
print test.read()
test.close()

"""
my result -->
Hello World!
--------------------
Hello World!
hello world!
"""

thanks I try that and it worked on my program

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.