How to create content and write to a txt file using Python?
You can use the built-in functions open() and write() in Python to create content and write it to a txt file.
Firstly, use the open() function to open the txt file, specifying the file name and writing mode (“w” indicates writing mode). If the file does not exist, the open() function will create a new file.
Next, use the write() function to write the content to the file.
Finally, close the file using the close() function to ensure that the write operation has been completed.
Here is an example code:
# 打开文件
file = open("example.txt", "w")
# 写入内容
file.write("Hello, World!")
# 关闭文件
file.close()
After running, a text file named “example.txt” will be created in the current directory with the text “Hello, World!” written in it.
Please note that when using the write() function in Python, the content is written in the form of a string. So, if you want to write other data types (like numbers), you need to convert them to strings first.