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?

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())

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
'''
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.