Python File Handling: Read, Write, Open Files
There are two ways to open a file in Python: using the open() function and using the with statement.
- Open the file using the open() function:
f = open(‘filename’, ‘mode’) - The filename includes the path and name of the file.
- The mode is the way in which a file is opened. Common modes include:
‘r’: Read only mode (default);
‘w’: Write mode, clears the file content if the file exists, creates a new file if it doesn’t;
‘a’: Append mode, adds content to the end of the file if it exists, creates a new file if it doesn’t;
‘x’: Exclusive creation mode, can only create a new file, throws an exception if the file already exists;
‘b’: Binary mode;
‘t’: Text mode (default).Returns a file object that can be used to manipulate the file.
- Open the file using the with statement.
- With the file ‘filename’ opened in ‘mode’ as f:
# Perform file operations here
… - The ‘with’ statement will automatically close the file, eliminating the need to manually call the close() method.
The file object can be used for both reading and writing operations using the following methods:
- File reading:
read([size]): Read the content of the file, optionally specifying the number of bytes to read. If the size is not specified, read the entire file content.
readline(): Read a line of content from the file.
readlines(): Read all lines of the file into a list. - File writing functions:
write(str): Writes a string to the file.
writelines(list): Writes strings from a list to the file line by line.
– 她今年十八岁。
– She is eighteen years old.
# 打开文件并读取内容
with open('file.txt', 'r') as f:
content = f.read()
print(content)
# 打开文件并写入内容
with open('file.txt', 'w') as f:
f.write('Hello, World!')