SoFunction
Updated on 2025-04-11

Basic methods for using Python to read and write files

1. File reading:

# Open the filewith open('', 'r') as file:
    # Read all the contents of the file    content = ()
    print(content)

    # Reset the file pointer to the beginning of the file    (0)
    # Read file content line by line    lines = ()
    for line in lines:
        print(())  # Remove line breaks at the end of the line
    # Reset the file pointer to the beginning of the file    (0)
    # Another way to read file content line by line    for line in file:
        print(())

Code explanation

  • open('', 'r'): in read-only moderOpen the namefile.
  • withStatement: Ensure that the file is automatically closed after use to avoid resource leakage.
  • (): Read all the contents of the file.
  • (0): Reset the file pointer to the beginning of the file for rereading.
  • (): Read the file contents by line and store them in a list, each line being an element of the list.
  • for line in file: Read the file content line by line,fileObjects are iterable, returning one row per iteration.

2. File writing:

# Open the file for writingwith open('', 'w') as file:
    # Write content    ("Hello, World!\n")
    ("This is a new line.")

Code explanation

  • open('', 'w'): In write modewOpen the file, if the file does not exist, the file will be created; if the file exists, the original file content will be cleared.
  • (): Write the specified content to the file, and newlines will not be added automatically. If a newline is required, it needs to be added manually.\n

3. File append:

# Open the file and add itwith open('', 'a') as file:
    # Add content    ("\nThis is an appended line.")

Code explanation

  • open('', 'a'): In addition modeaOpen the file and add new content at the end of the file, which will not overwrite the original file content.

4. Binary mode of file reading and writing:

# Read files in binary modewith open('', 'rb') as file:
    binary_data = ()
    print(binary_data)

# Write files in binary modewith open('', 'wb') as file:
    binary_data = b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64'  # Binary data    (binary_data)

Code explanation

  • open('', 'rb'): in binary read-only moderbOpen the file.
  • open('', 'wb'): Write mode in binarywbOpen the file.
  • b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64': represents binary data, usebPrefix.

5. Use the json module to read and write JSON files:

import json

# Write JSON datadata = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('', 'w') as file:
    (data, file)

# Read JSON datawith open('', 'r') as file:
    loaded_data = (file)
    print(loaded_data)

Code explanation

  • (data, file): Add Python objectsdataSerialize to JSON format and write to the file.
  • (file): Read JSON data from a file and parse it into a Python object.

6. Use the csv module to read and write CSV files:

import csv

# Write CSV datadata = [['Name', 'Age', 'City'], ['John', 30, 'New York'], ['Jane', 25, 'Chicago']]
with open('', 'w', newline='') as file:
    writer = (file)
    (data)

# Read CSV datawith open('', 'r') as file:
    reader = (file)
    for row in reader:
        print(row)

Code explanation

  • (file): Create a CSV write object and write a list of data to a file.
  • (data): Write each line in the data list to the file.
  • (file): Create a CSV reading object and read the file line by line.

7. Use the pandas module to read and write files (the pandas library needs to be installed):

import pandas as pd

# Write data to CSV filedata = {'Name': ['John', 'Jane'], 'Age': [30, 25], 'City': ['New York', 'Chicago']}
df = (data)
df.to_csv('data_pandas.csv', index=False)

# Read CSV filedf_read = pd.read_csv('data_pandas.csv')
print(df_read)

Code explanation

  • (data): Convert dictionary data topandasofDataFrameObject.
  • df.to_csv('data_pandas.csv', index=False):WillDataFrameObjects are stored as CSV files and do not save the index.
  • pd.read_csv('data_pandas.csv'): Read the CSV file asDataFrameObject.

8. Use the pickle module to serialize and deserialize objects:

import pickle

# Serialize objectsdata = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('', 'wb') as file:
    (data, file)

# Deserialize objectswith open('', 'rb') as file:
    loaded_data = (file)
    print(loaded_data)

Code explanation

  • (data, file): Add Python objectsdataSerialize to binary data and write to a file.
  • (file): Read binary data from a file and deserialize it into a Python object.

The above are common methods for reading and writing files in Python. You can choose the appropriate method to operate according to different file types and usage scenarios.

at last

Depending on file type and operation requirements, you can flexibly use the built-in open function and related modules, such as json, csv, pandas and pickle, and use the with statement to ensure the correct opening and closing of the file. Have you got it? Welcome to follow Wei Ge Ai Programming. We are moving side by side on the entire stack.

The above is the detailed content of the basic method of using Python to read and write files. For more information about reading and writing Python files, please pay attention to my other related articles!