SoFunction
Updated on 2025-04-10

Python file operation basics and exception handling

In this article, we will introduce how to do it in detailOpen the fileRead and write files, and howHandle exceptions in file operations

1. Open the file: open()

open()The function is used to open the file and return aFile Object, you can manipulate file content through this object. When opening a file, you need to specify the file path and operation mode.

grammar:

file_object = open(file_path, mode)

Common operating modes:

model describe
'r' Read the file (default mode), the file must exist.
'w' Write to the file, clear the content if the file exists; create if the file does not exist.
'a' Append mode to add new content to the end of the file.
'b' Binary mode, used to operate non-text files (such as pictures, audio).
'rb' Read the file in binary mode.
'wb' Write to the file in binary mode.

Example: Open a file for reading:

file = open('', 'r')  # Open the file for readingprint(())               # Print file content()                     # Close the file

Notice: If you forget to close the file, it may occupy system resources or cause data to be not written to disk in time.

2. Use the with statement to automatically manage files

usewithWhen a statement opens a file, Python will automatically close the file after the code block is over to avoid forgetting to call it.close()

Read file content:

with open('', 'r') as file:
    content = ()  # Read the entire file content    print(content)  # Print file content

Write file content:

with open('', 'w') as file:
    ('Hello, Python!\n')  # Write a line of text

Additional content:

with open('', 'a') as file:
    ('This is a new line.\n')  # Append a line at the end of the file

3. Different ways to read files

Python provides a variety of ways to read file contents, suitable for different scenarios.

method describe Example
read() Read the entire file content as a string content = ()
readline() Read a line of the file line = ()
readlines() Read all rows and return to the list lines = ()

Example: Read file line by line:

Example 1

with open('', 'r') as file:
    for line in file:
        print(())  # Remove line breaks and print each line

Example 2

with open('', 'r') as file:
    while True:
        line = ()  # Read a line        if not line:  # If it is an empty string, the file ends            break
        print(())  # Print the current line content

Tip: If it is used in a certain system,~Symbols (representing the user's home directory) are not usually recognized directly in the file path, and are improved by the following scheme.

import os
path = ("~/")
with open(path, 'r') as file:
    ......

4. File exception handling

An error may be encountered during file operations, such as the file does not exist or does not have permissions. We can usetry-exceptStatements to catch these exceptions and avoid program crashes.

Common exceptions:

  • FileNotFoundError: The file does not exist.
  • PermissionError: No permission to access the file.

Example: Catch file exception:

try:
    with open('', 'r') as file:
        content = ()
        print(content)
except FileNotFoundError:
    print("Error: The file does not exist. Please check the path.")
except PermissionError:
    print("Error: No permission to read the file.")
except Exception as e:
    print(f"Another error occurred:{e}")

5. Binary file operation

For non-text files (such as pictures or audio), you need toBinary modeRead and write.

Example: Reading a binary file:

with open('', 'rb') as file:
    data = ()
    print(data[:10])  # Print the first 10 bytes of data

Example: Write to a binary file:

with open('', 'wb') as file:
    with open('', 'rb') as src:
        (())  # Copy the picture

6. File path description

existopen(), the file path can beAbsolute pathorRelative path

  • Absolute path: The complete path from the root directory.
    Example:open('/Users/user/documents/', 'r')

  • Relative path: Path relative to the current working directory.
    Example:open('', 'r')

If there is aChinese or space, can be usedOriginal stringr'') Avoid escape errors:

with open(r'C:\User\Document\File.txt', 'r') as file:
    print(())

7. Summary

Common file operation steps:

  • useopen()orwithStatement opens the file.
  • Select the appropriate read or write mode ('r''w''a'wait).
  • useread()write()readlines()and other methods to operate.
  • If usedopen(), after the operation is completed, you must call itclose()Close the file.
  • usetry-exceptCapture exceptions in file operations.

Complete code example:

try:
    with open('', 'r') as file:
        print("File Content:")
        print(())
except FileNotFoundError:
    print("The file does not exist, please check the path.")
except PermissionError:
    print("No permission to access the file.")
except Exception as e:
    print(f"An unknown error occurred:{e}")

8. Tips

  • Be careful when operating files:Write mode'w'The file content will be cleared. Please confirm that it is correct before using it.
  • Handle line breaks: When reading text, you can usestrip()Remove excess line breaks.
  • Binary operations: When processing non-text files such as pictures, audio, etc., remember to use'rb'or'wb'

This is the article about the basics of Python file operation and exception handling. For more related basics of Python file operation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!