Home >Backend Development >Python Tutorial >How Can I Write Strings to Text Files in Python?
Writing Strings to Text Files in Python
In Python, you can write the value of a string variable, such as TotalAmount, into a text document. Here's how:
Using a context manager ensures that the file is always closed:
with open("Output.txt", "w") as text_file: text_file.write("Purchase Amount: %s" % TotalAmount)
If you're using Python2.6 or higher, use str.format():
with open("Output.txt", "w") as text_file: text_file.write("Purchase Amount: {0}".format(TotalAmount))
In Python2.7 and higher, use {0} or {}:
with open("Output.txt", "w") as text_file: text_file.write("Purchase Amount: {}".format(TotalAmount))
In Python3, use the optional file parameter with print():
with open("Output.txt", "w") as text_file: print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Or, use f-strings in Python3.6:
with open("Output.txt", "w") as text_file: print(f"Purchase Amount: {TotalAmount}", file=text_file)
The above is the detailed content of How Can I Write Strings to Text Files in Python?. For more information, please follow other related articles on the PHP Chinese website!