Home > Backend Development > Python Tutorial > How Can I Write Strings to Text Files in Python?

How Can I Write Strings to Text Files in Python?

Susan Sarandon
Release: 2024-12-14 19:05:11
Original
596 people have browsed it

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)
Copy after login

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))
Copy after login

In Python2.7 and higher, use {0} or {}:

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {}".format(TotalAmount))
Copy after login

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)
Copy after login

Or, use f-strings in Python3.6:

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template