Basic operations on files in Python

  1. open a file:

You can use the open() function to open a file and specify the mode and file name to open the file:

# 打开文件
file = open("filename.txt", "r")

Among them, the first parameter is the file name, and the second parameter is the mode for opening the file. Commonly used modes are:

  • "r": Read-only mode. In this mode, the file pointer starts from the beginning of the file. If the file does not exist, an error will be reported.
  • "w": Write mode, if the file does not exist, the file will be automatically created, if the file exists, the file content will be overwritten.
  • "a": Append mode. In this mode, the file pointer starts from the end of the file. If the file does not exist, the file will be automatically created.
  • "x": Exclusive mode, creates a new file with the specified file name. If the file already exists, an error will be reported.
  1. Close the file:

Use the close() function to close an already open file:

# 关闭文件
file.close()
  1. Read the file:

Use the read() function to read the contents of the file:

# 读取整个文件
content = file.read()
print(content)

You can also use the readline() function to read the contents of a file line by line:

# 逐行读取文件
line = file.readline()
while line:
    print(line)
    line = file.readline()
  1. Write to file:

Use the write() function to write content to the file:

# 写入文件
file.write("Hello World!")
  1. Delete Files:

Use the remove() function in the os module to delete files:

# 删除文件
import os
os.remove("filename.txt")
  1. Merge the contents of two files

You can use the with open statement to open two files in append mode, read their contents and write them line by line into a new merged file, and finally close the three files.

Code example:

with open("file1.txt", "r") as file1, open("file2.txt", "r") as file2, open("merged_file.txt", "a") as merged_file:
    for line in file1:
        merged_file.write(line)
    for line in file2:
        merged_file.write(line)
  1. Compare the contents of two files

You can use the with open statement to read two files line by line, compare each line, and output the number and line content of different lines if they are different. If the lengths of the two files are different, an IndexError will occur during comparison. You can output "File lengths are different" while catching this exception.

Code example:

with open("file1.txt", "r") as file1, open("file2.txt", "r") as file2:
    try:
        for i, (line1, line2) in enumerate(zip(file1, file2)):
            if line1 != line2:
                print("Line {} in file1 is different from line {} in file2".format(i+1, i+1))
                print("File1: {}".format(line1.rstrip()))
                print("File2: {}".format(line2.rstrip()))
    except IndexError:
        print("Files have different lengths")
  1. Read Excel content and structure it

You can use the openpyxl library to read an Excel file and then read the data in each worksheet line by line and store the data in a list. Finally, a dictionary is returned, the key of the dictionary is the worksheet name, and the value is a list composed of data.

Code example:

from openpyxl import load_workbook

def read_excel(file_path):
    workbook = load_workbook(file_path)
    data = {
    
    }
    for sheet_name in workbook.sheetnames:
        sheet = workbook[sheet_name]
        rows = []
        for row in sheet.iter_rows():
            row_data = []
            for cell in row:
                row_data.append(cell.value)
            rows.append(row_data)
        data[sheet_name] = rows
    return data
  1. Count files of a specified size in a directory and return a collection

You can use the functions in the os library and the os.path module to traverse all files in the directory, determine whether the file size meets the requirements, and add the file paths that meet the requirements into a set and return it.

Code example:

import os

def find_files_by_size(start_dir, size):
    files = set()
    for root, dirs, filenames in os.walk(start_dir):
        for filename in filenames:
            file_path = os.path.join(root, filename)
            file_size = os.path.getsize(file_path)
            if file_size == size:
                files.add(file_path)
    return files
  1. Quickly replace specified characters in a file

You can use the with open statement to open a file in read-write mode, find the specified characters in each line and replace them with new characters, and finally close the file.

Code example:

with open("file.txt", "r+") as file:
    lines = file.readlines()
    file.seek(0)
    for line in lines:
        new_line = line.replace("old", "new")
        file.write(new_line)
    file.truncate()

Guess you like

Origin blog.csdn.net/u012534326/article/details/131246369