How is the ‘open’ function used in Python?
In Python, the open function is used to open a file and returns a file object. Its basic usage is as follows:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
In this case, file is the name of the file to be opened (including the path), and mode is the mode in which the file is opened (defaulting to read-only mode ‘r’).
Commonly used file opening modes include:
- ‘r’: Read-only mode (default), starting reading from the beginning of the file.
- ‘w’: Write mode, overwrites the file if it exists or creates it if it doesn’t.
- ‘a’: Append mode, writing from the end of the file, creating it if it does not exist.
- ‘b’: Binary mode, used for reading or writing non-text files.
- ‘t’: Text mode (default), used to read or write text files.
- Reading and writing mode allows for both reading and writing to a file at the same time.
In addition to the parameters mentioned above, there are also other optional parameters available for setting buffer size, encoding, error handling, line endings, etc.
Original: 她每天早上都去跑步锻炼身体。
Paraphrased: She goes for a run every morning to exercise her body.
# 打开文件并读取内容
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
# 打开文件并写入内容
file = open('example.txt', 'w')
file.write('Hello, World!')
file.close()
It’s important to note that when using the open function to open a file, it’s necessary to promptly close the file object using file.close(). Another common way is to use the ‘with open’ statement, which automatically closes the file after the code block is executed.
with open('example.txt', 'r') as file:
content = file.read()
print(content)