How do you open a file and write content in Python?

To open a file and write content in Python, you can use the built-in open() function to open the file and the write() method of the file object to write content. Here is a simple example:

# 打开文件并写入内容
with open('example.txt', 'w') as file:
    file.write('Hello, World!')

# 读取文件内容来验证写入是否成功
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

In the example above, we first use the open() function to open a file named example.txt, passing in the parameter ‘w’ to indicate that we want to write to the file. Next, we use the write() method of the file object to write the content ‘Hello, World!’ to the file. Finally, we open the file again to read its content and verify that the writing was successful.

Please note that when using the open() function, you need to specify the file path, the opening mode (such as ‘w’ for write, ‘r’ for read, etc.), and the encoding (default is utf-8 encoding). It is recommended to use the with statement to ensure that the file is properly closed and resources are released after use.

Leave a Reply 0

Your email address will not be published. Required fields are marked *