How do you write content to a txt file in Python?

You can use Python’s file manipulation feature to write content to a txt file. Here is a simple example:

# 打开文件,如果文件不存在则创建新文件
file = open("example.txt", "w")

# 写入内容
file.write("Hello, World!\n")
file.write("This is an example.")

# 关闭文件
file.close()

The above code will create a file named example.txt in the current directory and write the content “Hello, World!\nThis is an example.” into the file.

If you want to write the value of a variable to a file, you can use string formatting.

# 打开文件,如果文件不存在则创建新文件
file = open("example.txt", "w")

# 定义变量
name = "Alice"
age = 25

# 将变量的值写入文件中
file.write(f"Name: {name}\n")
file.write(f"Age: {age}")

# 关闭文件
file.close()

In the code above, the values of the variables name and age are written to a file. The result is as follows:

Name: Alice
Age: 25
bannerAds