0

i have 5 variables and i want to write them all to a text file using 1 line of code rather than repeating the x.write() function 5 times. Im really not sure how to do this please help

1
  • Take a look at the Python writelines method. Commented May 25, 2017 at 18:36

2 Answers 2

4
with open('path/to/file', 'w') as outfile:
    outfile.write("{}{}{}{}{}\n".format(var1, var2, var3, var4, var5))

vars = (var1, var2, var3, var4, var5)
with open('path/to/file', 'w') as outfile:
    outfile.write(''.join([str(i) for i in vars]))
Sign up to request clarification or add additional context in comments.

Comments

2

If you're using Python 3.6 or newer, you can use PEP-498 F-strings, to do it concisely

with open("path/to/file", "w") as f:
    f.write(f"{var1}{var2}{var3}{var4}{var5}")

Comments

Your Answer

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.