5.文件操作

七言 2025-8-1 15 8/1

[TOC]

文件操作

打开文件

  • 使用open()函数,可以打开一个已经存在的文件,或者创建一个文件
  • 当使用open()函数时,务必记得在操作完成后关闭文件,除非使用了with语句,它会自动处理关闭过程。
  • 文件编码(如'utf-8')对于读写文本文件非常重要,特别是在处理非ASCII字符时

基本语法

file_object = open(file_name, mode='r', encoding='encoding_type')
*   file_name:是要打开的目录文件名或者完整路径(文件所在的具体路径)
*   mode:设置打开文件的模式(访问模式):
    *   'r': 只读模式,默认值
    *   'w': 写入模式,如果文件已存在,则会被覆盖;如果不存在,则创建新文件
    *   'a': 追加模式,向文件末尾添加内容,不会覆盖现有内容
    *   'b': 二进制模式,用于非文本文件(如图片、音频等)
    *   '+': 更新模式,用于读写操作
    *   模式可以组合,如'rb'表示以二进制模式读取文件;'r+'表示打开一个文件用于读写,文件指针放在文件开头;'a+'表示打开一个文件用于读写,文件指针放在文件末尾
*   encoding: 编码类型,如'utf-8'、'gbk'等,用于处理文本文件

示例

# f是open函数的文件对象
f = open('test.txt','w')

读写操作

文件写

基本语法

文件对象.write('内容')
*   如果文件存在,w模式先清空再写入
*   r模式:如果文件不存在则会报错

示例

# 1.打开文件
f = open('test.txt','w')

# 2.文件写入
f.write('Hello Python')

# 3.关闭文件
f.close()

文件读

基本语法

文件对象.read(num)
*   num: 表示要从文件中读取的数据的长度(单位是字节)
*   如果没有传入 num ,那么就表示读取文件中所有的数据

readlines()

  • readlines()方法用于从文件中读取所有行,并将它们存储为一个列表,其中列表中的每个元素都是文件中的一行(包括行尾的换行符\n)

示例

f =open('test.txt','r')
content = f.readlines()
# 打印结果['helloworldpython\n', 'test\n']
print(content)
# 关闭文件
f.close()
*   当调用readlines()时,它会读取整个文件并将其加载到内存中,因此如果文件非常大,这可能会导致程序消耗大量内存
  • 建议使用其他方法来逐行读取文件,例如:
with open('large_file.txt', 'r', encoding='utf-8') as file:
    for line in file:
        process_line(line)  # 处理每一行

关闭文件

基本语法

文件对象.close()

with open()

  • 使用with语句可以自动管理文件的打开和关闭,即使在读写过程中发生异常,也能确保文件被正确关闭
  • 了with语句会自动帮我们调用close()方法

基本语法

with open() as 文件

示例

# 写入文本
with open('output.txt', 'w', encoding='utf-8') as file:
    file.write('Hello, world!\n')
    file.write('Welcome to Python programming.\n')

# 追加内容到文件
with open('output.txt', 'a', encoding='utf-8') as file:
    file.write('More text added to the end of the file.\n')

获取文件路径

os.path.abspath(path)

  • os.path.abspath(path):获取当前文件或者任意给定文件的绝对路径

示例

import os

# 当前工作目录下的相对路径
relative_path = "documents/example.txt"

# 转换为绝对路径
absolute_path = os.path.abspath(relative_path)

print(absolute_path)  # 输出: /home/user/documents/example.txt (取决于当前工作目录)

# 对于已经在绝对路径的情况
already_absolute_path = "/home/user/documents/example.txt"

# os.path.abspath() 将返回相同的路径,但会规范化它
normalized_path = os.path.abspath(already_absolute_path)

print(normalized_path)  # 输出: /home/user/documents/example.txt

os.path.dirname(path)

  • os.path.dirname(path): 获取当前文件的目录路径,返回路径中最后一个斜杠之前的所有内容

示例

import os

# 定义一个路径
path = "/home/user/documents/example.txt"

# 使用 os.path.dirname() 提取目录名
directory = os.path.dirname(path)

print(directory)  # 输出: /home/user/documents

# 如果路径是一个相对路径
relative_path = "documents/example.txt"

# 同样可以使用 os.path.dirname()
relative_directory = os.path.dirname(relative_path)

print(relative_directory)  # 输出: documents

os.path.join(path1, path2, ...)

  • os.path.join(path1, path2, ...):把目录和文件名合成一个路径

示例

import os

# 假设当前目录为 /home/user

# 在 Unix/Linux/macOS 中,使用斜线作为分隔符
path1 = os.path.join("/home", "user", "documents")
print(path1)  # 输出: /home/user/documents

# 在 Windows 中,使用反斜线作为分隔符
path2 = os.path.join("C:", "Users", "YourName", "Documents")
print(path2)  # 输出: C:\Users\YourName\Documents

# 使用多个参数时,它们都会被正确地连接起来
path3 = os.path.join("C:", "", "Users", "YourName", "Documents")
print(path3)  # 输出: C:\Users\YourName\Documents

# 如果某个部分以路径分隔符结尾,它会被正确处理
path4 = os.path.join("C:", "Users", "YourName\\", "Documents")
print(path4)  # 输出: C:\Users\YourName\Documents

综合示例

import os

# 返回目录路径
print(os.path.dirname(__file__)) 
base_path = os.path.dirname(__file__)

# 把生成的报告放到reports目录下
print(os.path.join(base_path, 'reports', 'report.txt')) # 将目录和文件名合成一个路径
print(os.path.abspath(__file__)) # 输出绝对路径
*   __file__ 是一个特殊变量,它包含了当前脚本的文件名
  • 对于获取其他文件的绝对路径,你需要提供相对于当前工作目录的相对路径,或者直接提供完整的路径。如果文件不在当前工作目录下,你需要确保提供的路径是正确的,否则os.path.abspath()将返回基于当前工作目录的路径,而不是实际存在的文件路径

示例

# 假设你有一个名为data.txt的文件位于与你的脚本同一目录下的data子目录中

import os

# 指定文件的相对路径
relative_path = "./data/data.txt"

# 获得该文件的绝对路径
absolute_path = os.path.abspath(relative_path)

print("The absolute path is:", absolute_path)

os.getcwd()

  • 如果你不确定当前工作目录是什么,也可以使用os.getcwd()来获取当前工作目录的路径,然后结合os.path.join()来构建文件的完整路径

示例

import os

# 获取当前工作目录
current_working_dir = os.getcwd()

# 构建文件的完整路径
file_name = "file.txt"
full_path = os.path.join(current_working_dir, file_name)

# 转换为绝对路径
absolute_path = os.path.abspath(full_path)
print("Absolute path of the file:", absolute_path)
- THE END -

七言

8月01日16:48

最后修改:2025年8月1日
0

非特殊说明,本博所有文章均为博主原创。

共有 0 条评论