How can file read and write operations be performed in Python?

One of the main functions used in Python for file reading and writing operations is the built-in open() function. Here is a simple example:

  1. Read the contents of the file and print it out:
# 打开文件
with open('file.txt', 'r') as f:
    # 读取文件内容
    content = f.read()
    # 打印内容
    print(content)
  1. Write content to a file:
# 打开文件
with open('file.txt', 'w') as f:
    # 写入内容
    f.write('Hello, world!')

In the open() function, the first parameter is the file path and the second parameter is the mode for opening the file. Common modes include ‘r’ for reading, ‘w’ for writing, ‘a’ for appending to the end of the file, ‘rb’ for reading the file in binary mode, ‘wb’ for writing the file in binary mode, and so on.

It is important to note that after finishing file operations, make sure to call the close() method to close the file, or use the with statement to automatically close the file.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds