Detailed introduction to Python file operations (open, read, write, context manager, close, exception handling; file mode, encoding, path, read and write location, copy, move, delete)

Table of contents

1. Basic operations

1. Open the file

2. Read the file

3. Write to file

4. Context Manager

5. Close the file

6. Exception handling

2. Advanced operations

6. File mode

 7. File encoding processing

8. File path operations

9. Reading and writing locations of files

10. Iterate over file contents

11. Copy, move and delete files


1. Basic operations

1. Open the file

        Use built-in functions open()to open a file and return a file object. You need to provide the path to the file and the opening mode (read, write, append, etc.).

file = open('file.txt', 'r')  # 以只读模式打开名为file.txt的文件

2. Read the file

        The file object provides multiple methods for reading file contents. Commonly used methods are:

content = file.read()  # 读取整个文件内容
line = file.readline()  # 读取文件的一行内容
lines = file.readlines()  # 读取文件的所有行内容并返回列表
  • read(): Read the contents of the entire file as a string.
  • readline(): Read the file contents line by line, one line at a time.
  • readlines(): Read the file contents line by line and return a list containing the contents of each line.

3. Write to file

write()Data can be written to a file         using the methods of the file object . You can pass strings or byte streams as parameters to write()methods.

file = open('file.txt', 'w')  # 以写入模式打开文件
file.write('Hello, World!')  # 写入字符串到文件

4. Context Manager

        When dealing with file operations, to ensure that files are properly closed after use, you can use a context manager to automatically manage the opening and closing of files. Using withstatements you can create a context manager and automatically close the file after a block of code has finished executing, without having to manually call close()methods.

with open('file.txt', 'r') as file:
    # 执行文件操作,文件会在代码块执行完毕后自动关闭

5. Close the file

        When you are finished working on a file, you should close the file to free up system resources. Files can be closed using close()the methods of the file object.

file.close()  # 关闭文件

6. Exception handling

        During the file operation process, some abnormal situations may occur, such as the file does not exist, permission errors, etc. You can use exception handling statements to catch and handle these exceptions.

try:
    file = open('file.txt', 'r')
    # 执行文件操作
except FileNotFoundError:
    print("文件不存在")
except PermissionError:
    print("没有文件访问权限")
finally:
    file.close()  # 确保文件被关闭

2. Advanced operations

6. File mode

        When opening a file, you need to specify the mode of the file. You can pass the mode to the open()function along with the path of the file to be opened, eg open('file.txt', 'r'). Common file patterns include:

  • 'r': Read-only mode (default). After opening the file, you can only read the file content and cannot write it.
  • 'w':Writing mode. If the file exists, the file content will be cleared first, and then new content will be written; if the file does not exist, a new file will be created.
  • 'a': Append mode. Appending new content at the end of the file will not clear the original content; if the file does not exist, a new file will be created.
  • 'x': Exclusive creation mode. Creates a new file, or fails to open if the file already exists.
  • 'b': Binary mode. Read or write files in binary format, such as reading image or video files.
  • 't': Text mode (default). Read or write files in text format, such as reading or writing strings.

 7. File encoding processing

        When processing text files, you need to consider the encoding format of the file. Python provides a variety of encoding processing methods, the common ones are:

  • ascii: ASCII encoding, suitable for English text.
  • utf-8: UTF-8 encoding, suitable for text in multiple languages.
  • latin-1: Latin-1 encoding, suitable for text in Western European languages.

When opening a file, you can specify the file's encoding format.

with open('file.txt', 'r', encoding='utf-8') as file:
    # 处理文件内容

8. File path operations

        In file operations, you often need to deal with file paths and file names. Python provides osmodules and os.pathmodules for file path operations. You can use these modules to get the absolute path of a file, check if a file exists, create a directory, etc.

import os

file_path = 'path/to/file.txt'
abs_path = os.path.abspath(file_path)  # 获取文件的绝对路径
file_exists = os.path.exists(file_path)  # 检查文件是否存在
dir_name = os.path.dirname(file_path)  # 获取文件所在目录的路径
os.makedirs('path/to/new_dir')  # 创建目录

9. Reading and writing locations of files

        The file object maintains a read and write location pointer, indicating the location of the next read or write operation. When reading the file content, the pointer will move backward with the number of bytes read; when writing the file content, the pointer will move to the new position after writing. You can use seek()the methods of the file object to change the position of the pointer in order to read or write data at a specific location. For example:

with open('file.txt', 'r') as file:
    file.seek(10)  # 将指针移动到文件的第10个字节处
    data = file.read()  # 从第10个字节开始读取文件内容

10. Iterate over file contents

        File objects can be iterated over like iterators, reading the file contents line by line. This is useful when working with large files, as there is no need to read the entire file into memory at once.

with open('file.txt', 'r') as file:
    for line in file:
        # 处理每一行内容

11. Copy, move and delete files

        During file operations, you may need to copy the file to another location or move the file to a different directory. Python provides shutilmodules to handle operations such as copying, moving, and deleting files.

import shutil

# 复制文件
shutil.copy('source.txt', 'destination.txt')

# 移动文件
shutil.move('file.txt', 'new_dir/file.txt')

# 删除文件
os.remove('file.txt')

Guess you like

Origin blog.csdn.net/m0_63834988/article/details/133253195