BaRud
BaRud

Reputation: 3218

write to file in python3

I am a python beginner. I am writing to a file as:

   with open("Init", mode='w') as out:
     out.write(datName)
     out.write("\n")
     out.write("T\n")
     out.write(datGroup)
     out.write("\n")
     out.write(datLatx) 
     out.write("  ")

while this is working, it is looking bad (space and newline is separate write statement).

I read this page, but still no idea.

Is there a better way of doing this given out.write(datName"\n") is invalid?

Upvotes: 1

Views: 1814

Answers (2)

jfs
jfs

Reputation: 414139

If you want the output of many print statements to be redirected to a file, you could use contextlib.redirect_stdout() in Python 3.4+, for older Python versions see this answer:

from contextlib import redirect_stdout

with open('init.txt', 'w') as file, redirect_stdout(file):
    print(datName)
    print("T")
    print(datGroup)
    print(datLatx, end="  ")

You could also combine the print statements:

with open('init.txt', 'w') as file:
    print("\n".join([datName, "T", datGroup, datLatx]),
          end="  ", file=file)

Upvotes: 0

nneonneo
nneonneo

Reputation: 179392

Well, you could do

out.write(datName + "\n")

but it may be easier to just use print:

print(datName, file=out)

as print automatically appends a newline.

Upvotes: 1

Related Questions