1

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?

BaRud
  • 3,055
  • 7
  • 41
  • 89

2 Answers2

1

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.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
0

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)
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670