0

Ive noticed print() includes linebreaks, and its real easy to suppress them.
Is there a way I can write lines to a file, but have the line breaks includes implicitly?

eg:

file=open("testfile.txt","w")
file.write("line 1")
file.write("line 2")
file.write("line 3")
file.close()

meanwhile the file will contain

line 1\nline 2\nline 3\n

Is this possible in python?

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by vegaseat
0

There is possible to use file as output in print statement, but it becomes cumbersome with many prints. Maybe something like this?

with open("testfile.txt","w") as myfile:
    myfile.write("""\
line 1
line 2
line 3
""")

with open("testfile.txt") as myfile:
    print(myfile.read())

with open("testfile2.txt","w") as myfile:
    for line in ("line 1", "line 2", "line 3"):
        myfile.write(line+'\n')

with open("testfile2.txt") as myfile:
    print(myfile.read())

Edited by pyTony: n/a

0

Some other options ...

with open("testfile4.txt","w") as myfile:
    for line in ("line 1", "line 2", "line 3"):
        # python2
        print >>myfile, line
        # python3
        #print(line, file=myfile)

with open("testfile4.txt") as myfile:
    print(myfile.read())

'''
line 1
line 2
line 3
'''
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.