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?

asked Apr 8, 2014 at 23:01

2 Answers 2

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.

answered Apr 8, 2014 at 23:02
Sign up to request clarification or add additional context in comments.

Comments

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)
answered Apr 8, 2014 at 23:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.