ZAYN YUSAF
ZAYN YUSAF

Reputation: 3

Writing multiple variables to a text file on seperate lines in python

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

Upvotes: 0

Views: 136

Answers (2)

user3665377
user3665377

Reputation:

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}")

Upvotes: 2

inspectorG4dget
inspectorG4dget

Reputation: 113905

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

Upvotes: 4

Related Questions