• 周六. 4月 20th, 2024

Python 文件操作的介绍

城主

12月 26, 2022 ,

在 Python 中,文件是存储在计算机存储系统上的字节序列。它可以包含文本、数据或两者的组合。你可以使用 Python 内置的 openreadwrite 函数读取和写入文件。

下面是一个使用这些函数读取和写入文件的示例:





# 以只读模式打开文件
with open('file.txt', 'r') as f:
    # 读取文件内容
    contents = f.read()
    print(contents)

# 以写入模式打开文件
with open('file.txt', 'w') as f:
    # 向文件写入一些文本
    f.write('你好,世界!')

你还可以使用 'a' 模式打开文件,以追加模式打开文件,这样你就可以在文件末尾添加新内容,而不会覆盖其现有内容。

对于更高级的文件处理,你可以使用 Python 标准库中的 io 模块。

在 Python 中,文件还有一些其他的操作,例如:

  • seek 函数:可以改变当前文件读取/写入位置。
  • truncate 函数:可以将文件截断到指定大小。
  • tell 函数:可以返回当前文件读取/写入位置。

例如:





# Open the file in write mode
with open('file.txt', 'w') as f:
    # Write some text to the file
    f.write('Hello, world!\n')
    f.write('This is a test.\n')

    # Get the current position of the file pointer
    pos = f.tell()
    print(f'Current position: {pos}')
    
    # Seek to the beginning of the file
    f.seek(0)
    
    # Overwrite the first line
    f.write('Goodbye, world!\n')
    
    # Truncate the file to the current position
    f.truncate()

此外,你还可以使用 Python 的 with 语句和上下文管理器来简化文件的打开和关闭操作,这样可以避免忘记关闭文件的问题。

阅读  Python运算符的详细用法

最后,请注意,在操作文件时,需要考虑文件权限的问题,例如文件是否可读、可写等。

除了使用内置的文件操作函数之外,Python 还提供了许多用于处理文件的模块和库。例如:

  • csv 模块:可以用于读取和写入 CSV 格式的文件。
  • json 模块:可以用于读取和写入 JSON 格式的文件。
  • pickle 模块:可以用于将 Python 对象序列化为二进制数据并写入文件,也可以从文件中读取并反序列化为 Python 对象。

例如,你可以使用 csv 模块将数据写入 CSV 文件,然后使用 json 模块将数据读取出来:





import csv
import json

# Write a list of dictionaries to a CSV file
data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

with open('data.csv', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=['name', 'age'])
    writer.writeheader()
    writer.writerows(data)

# Read the data back from the CSV file and convert it to JSON format
with open('data.csv', 'r') as f:
    reader = csv.DictReader(f)
    data = [row for row in reader]

json_data = json.dumps(data)
print(json_data)

此外,还有许多其他用于处理文件的模块和库,例如 xlrdxlwt 用于处理 Excel 文件,pdfminer 用于处理 PDF 文件等。

阅读  Python 多态使用方法详解

在处理文件时,有时你可能需要处理文件路径。在 Python 中,你可以使用 os 模块中的函数来操作文件路径。

例如,你可以使用 os.path.join 函数来将文件名与路径拼接起来,这样就可以在不同的操作系统中使用相同的代码了:





import os

filename = 'data.csv'
path = '/home/user/documents'

# Join the path and filename
full_path = os.path.join(path, filename)

# Open the file
with open(full_path, 'r') as f:
    # Read the contents of the file
    contents = f.read()
    print(contents)

此外,你还可以使用 os.path.split 函数来将文件路径拆分为路径和文件名,或者使用 os.path.abspath 函数来获取文件的绝对路径。

最后,如果你需要创建、删除或重命名文件或目录,你还可以使用 os 模块中的函数 os.mkdiros.rmdiros.rename

在处理文件时,你还可能会遇到文件压缩和解压缩的问题。在 Python 中,你可以使用 zipfile 模块来压缩和解压缩文件。

例如,你可以使用 zipfile.ZipFile 类来创建压缩文件,并使用 write 方法来将文件添加到压缩文件中:





import zipfile

# Create a new ZIP file
with zipfile.ZipFile('files.zip', 'w') as zf:
    # Add a file to the ZIP file
    zf.write('file1.txt')
    zf.write('file2.txt')

你也可以使用 zipfile.ZipFile 类来解压缩文件,并使用 extractall 方法将文件解压到指定目录中:





import zipfile

# Extract all files from a ZIP file
with zipfile.ZipFile('files.zip', 'r') as zf:
    zf.extractall('extracted_files')

此外,你还可以使用 zipfile.ZipFile.infolist 方法来获取压缩文件中的文件列表,或者使用 zipfile.ZipFile.getinfo 方法来获取单个文件的信息。

阅读  Python模块的详细用法