Python3入门指南Python语言的特点和实际应用Python3环境搭建配置VSCode进行Python开发Python基础语法Python变量与数据类型Python数据类型转换Python解释器使用Python注释使用Python运算符Python数字类型Python字符串操作Python列表操作Python元组使用Python字典使用Python集合使用Python条件控制详解Python循环语句详解Python编程入门实践Python推导式详解Python迭代器和生成器Python with语句详解Python函数详解Python lambda(匿名函数)Python装饰器Python数据结构Python模块和包使用Python中__name__和__main__的用法Python输入输出:从基础到文件操作Python文件操作Python OS模块使用Python错误和异常处理Python面向对象编程Python命名空间和作用域Python虚拟环境:venv详细教程Python类型注解Python标准库常用模块Python正则表达式Python CGI编程Python MySQL(mysql-connector驱动)Python MySQL(PyMySQL驱动)Python网络编程Python发送邮件Python多线程编程Python XML解析Python JSON解析Python日期和时间处理Python操作MongoDBPython urllib库使用Python uWSGI 安装与配置Python pip包管理工具Python operator模块Python math模块Python requests模块HTTP请求Python random模块Python OpenAI库Python AI绘画制作Python statistics模块Python hashlib模块:哈希加密Python量化交易Python pyecharts数据可视化Python Selenium网页自动化Python BeautifulSoup网页数据提取Python Scrapy爬虫框架Python Markdown转HTMLPython sys模块Python Pickle模块:数据存储Python subprocess模块Python queue队列模块Python StringIO内存文件操作Python logging日志记录Python datetime日期时间处理Python re正则表达式Python csv表格数据处理Python threading 多线程编程Python asyncio 异步编程Python PyQt 图形界面开发Python 应用方向和常用库框架

Python文件操作

文件操作是编程中的基础技能。Python提供了简单而强大的文件处理功能,让我们能够轻松地读取和写入文件。


打开文件

使用open()函数来打开文件,这个函数会返回一个文件对象。

基本语法

文件对象 = open(文件名, 模式)

文件打开模式

最常用的模式有:

  • 'r' - 只读模式(默认)

  • 'w' - 写入模式(会覆盖原有内容)

  • 'a' - 追加模式(在文件末尾添加内容)

  • 'x' - 创建新文件(如果文件已存在会报错)

  • 'b' - 二进制模式

  • '+' - 读写模式

实际示例

# 以只读方式打开文件
file = open('example.txt', 'r')

# 以写入方式打开文件(如果文件不存在会创建)
file = open('data.txt', 'w')

# 以追加方式打开文件
file = open('log.txt', 'a')

# 以二进制方式读取图片
file = open('image.jpg', 'rb')


读取文件内容

有多种方法可以读取文件内容。

读取整个文件

# 方法1:使用read()读取全部内容
file = open('example.txt', 'r', encoding='utf-8')
content = file.read()
print(content)
file.close()

# 方法2:使用with语句,自动关闭文件
with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)
# 文件会自动关闭,不需要调用close()

逐行读取

# 读取单行
with open('example.txt', 'r', encoding='utf-8') as file:
    first_line = file.readline()
    print("第一行:", first_line)

# 读取所有行到列表
with open('example.txt', 'r', encoding='utf-8') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())  # strip()移除首尾空白字符

# 直接遍历文件对象(推荐用于大文件)
with open('example.txt', 'r', encoding='utf-8') as file:
    for line_num, line in enumerate(file, 1):
        print(f"第{line_num}行: {line.strip()}")


写入文件

基本写入操作

# 写入模式(会覆盖原有内容)
with open('output.txt', 'w', encoding='utf-8') as file:
    file.write("这是第一行文本\n")
    file.write("这是第二行文本\n")
    number = 42
    file.write(f"这是一个数字:{number}\n")

# 追加模式(在文件末尾添加)
with open('output.txt', 'a', encoding='utf-8') as file:
    file.write("这是在末尾添加的内容\n")

写入多行内容

# 使用writelines方法
lines = [
    "第一行内容\n",
    "第二行内容\n", 
    "第三行内容\n"
]

with open('multi_line.txt', 'w', encoding='utf-8') as file:
    file.writelines(lines)

# 使用循环写入
data = ["苹果", "香蕉", "橙子", "葡萄"]
with open('fruits.txt', 'w', encoding='utf-8') as file:
    for fruit in data:
        file.write(fruit + '\n')


文件指针操作

文件指针表示当前读取或写入的位置。

获取和移动指针

with open('example.txt', 'r+', encoding='utf-8') as file:
    # 获取当前位置
    position = file.tell()
    print(f"当前位置:{position}")
    
    # 读取前10个字符
    content = file.read(10)
    print(f"前10个字符:{content}")
    
    # 移动到文件开头
    file.seek(0)
    print("移动后位置:", file.tell())
    
    # 移动到第5个字符
    file.seek(5)
    print("从第5个字符开始:", file.read())

实际应用示例

# 在文件特定位置插入内容
def insert_content(filename, position, new_content):
    with open(filename, 'r+', encoding='utf-8') as file:
        content = file.read()
        file.seek(0)
        file.write(content[:position] + new_content + content[position:])

# 使用示例
insert_content('test.txt', 5, '插入的内容')


二进制文件操作

处理图片、视频等非文本文件时,需要使用二进制模式。

# 复制图片文件
def copy_image(source, destination):
    with open(source, 'rb') as src_file:
        with open(destination, 'wb') as dst_file:
            content = src_file.read()
            dst_file.write(content)
    print(f"图片已从 {source} 复制到 {destination}")

# 使用示例
copy_image('photo.jpg', 'photo_backup.jpg')


实际应用案例

案例1:学生成绩管理系统

def save_student_scores(students, filename='scores.txt'):
    """保存学生成绩到文件"""
    with open(filename, 'w', encoding='utf-8') as file:
        file.write("姓名,语文,数学,英语\n")
        for name, scores in students.items():
            line = f"{name},{scores['chinese']},{scores['math']},{scores['english']}\n"
            file.write(line)
    print("学生成绩已保存")

def load_student_scores(filename='scores.txt'):
    """从文件加载学生成绩"""
    students = {}
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            lines = file.readlines()
            # 跳过标题行
            for line in lines[1:]:
                name, chinese, math, english = line.strip().split(',')
                students[name] = {
                    'chinese': int(chinese),
                    'math': int(math),
                    'english': int(english)
                }
    except FileNotFoundError:
        print("成绩文件不存在")
    return students

# 使用示例
students_data = {
    '张三': {'chinese': 85, 'math': 92, 'english': 78},
    '李四': {'chinese': 90, 'math': 88, 'english': 95},
    '王五': {'chinese': 76, 'math': 85, 'english': 80}
}

save_student_scores(students_data)
loaded_data = load_student_scores()

# 显示成绩
print("\n学生成绩:")
for name, scores in loaded_data.items():
    avg_score = (scores['chinese'] + scores['math'] + scores['english']) / 3
    print(f"{name}: 语文{scores['chinese']} 数学{scores['math']} 英语{scores['english']} 平均{avg_score:.1f}")

案例2:日志记录系统

def write_log(message, level="INFO", filename="app.log"):
    """写入日志文件"""
    from datetime import datetime
    
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"[{timestamp}] {level}: {message}\n"
    
    with open(filename, 'a', encoding='utf-8') as file:
        file.write(log_entry)
    
    print(f"日志已记录:{log_entry.strip()}")

def read_recent_logs(filename="app.log", lines=10):
    """读取最近的日志"""
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            all_lines = file.readlines()
            recent_lines = all_lines[-lines:] if len(all_lines) > lines else all_lines
            print(f"\n最近{len(recent_lines)}条日志:")
            for line in recent_lines:
                print(line.strip())
    except FileNotFoundError:
        print("日志文件不存在")

# 使用示例
write_log("应用程序启动")
write_log("用户登录成功", "INFO")
write_log("数据处理完成", "SUCCESS")
write_log("发现警告信息", "WARNING")

read_recent_logs(lines=5)

案例3:配置文件管理

def read_config(filename='config.ini'):
    """读取配置文件"""
    config = {}
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            for line in file:
                line = line.strip()
                if line and not line.startswith('#'):  # 跳过空行和注释
                    key, value = line.split('=', 1)
                    config[key.strip()] = value.strip()
    except FileNotFoundError:
        print("配置文件不存在")
    return config

def write_config(config, filename='config.ini'):
    """写入配置文件"""
    with open(filename, 'w', encoding='utf-8') as file:
        file.write("# 应用程序配置\n\n")
        for key, value in config.items():
            file.write(f"{key} = {value}\n")
    print("配置已保存")

# 使用示例
app_config = {
    'database_host': 'localhost',
    'database_port': '5432',
    'database_name': 'myapp',
    'debug_mode': 'True',
    'max_connections': '100'
}

write_config(app_config)
loaded_config = read_config()

print("\n当前配置:")
for key, value in loaded_config.items():
    print(f"{key}: {value}")


错误处理和最佳实践

正确处理文件操作错误

def safe_file_operation(filename, operation='read'):
    """安全的文件操作"""
    try:
        if operation == 'read':
            with open(filename, 'r', encoding='utf-8') as file:
                return file.read()
        elif operation == 'write':
            # 这里可以添加写入逻辑
            pass
    except FileNotFoundError:
        print(f"错误:文件 {filename} 不存在")
    except PermissionError:
        print(f"错误:没有权限访问文件 {filename}")
    except UnicodeDecodeError:
        print(f"错误:文件编码问题")
    except Exception as e:
        print(f"未知错误:{e}")
    return None

# 使用示例
content = safe_file_operation('example.txt')
if content:
    print("文件内容:", content)

重要建议

  1. 总是使用with语句:确保文件正确关闭,即使发生异常

  2. 指定文件编码:特别是处理中文时使用encoding='utf-8'

  3. 处理大文件要小心:不要一次性读取超大文件到内存

  4. 检查文件是否存在:在读取前确认文件存在

  5. 备份重要文件:在修改前做好备份

# 好的做法
with open('data.txt', 'r', encoding='utf-8') as file:
    for line in file:
        process_line(line)  # 逐行处理大文件

# 不好的做法
file = open('data.txt', 'r')
content = file.read()  # 可能内存溢出
file.close()

掌握这些文件操作技巧,你就能轻松处理各种文件读写任务。记住多练习,在实际项目中应用这些知识。


open() 方法

Python open() 方法用于打开一个文件,并返回文件对象。

在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。

注意:使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。

open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。

open(file, mode='r')

完整的语法格式为:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

参数说明:

  • file: 必需,文件路径(相对或者绝对路径)。
  • mode: 可选,文件打开模式
  • buffering: 设置缓冲
  • encoding: 一般使用utf8
  • errors: 报错级别
  • newline: 区分换行符
  • closefd: 传入的file参数类型
  • opener: 设置自定义开启器,开启器的返回值必须是一个打开的文件描述符。

mode 参数有:

模式描述
t文本模式 (默认)。
x写模式,新建一个文件,如果该文件已存在则会报错。
b二进制模式。
+打开一个文件进行更新(可读可写)。
U通用换行模式(Python 3 不支持)。
r以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等。
r+打开一个文件用于读写。文件指针将会放在文件的开头。
rb+以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。一般用于非文本文件如图片等。
w打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
w+打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb+以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
a打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

默认为文本模式,如果要以二进制模式打开,加上 b 。


file 对象

file 对象使用 open 函数来创建,下表列出了 file 对象常用的函数:

序号方法及描述
1

file.close()

关闭文件。关闭后文件不能再进行读写操作。

2

file.flush()

刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。

3

file.fileno()

返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。

4

file.isatty()

如果文件连接到一个终端设备返回 True,否则返回 False。

5

file.next()

Python 3 中的 File 对象不支持 next() 方法。

返回文件下一行。

6

file.read([size])

从文件读取指定的字节数,如果未给定或为负则读取所有。

7

file.readline([size])

读取整行,包括 "\n" 字符。

8

file.readlines([sizeint])

读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。

9

file.seek(offset[, whence])

移动文件读取指针到指定位置

10

file.tell()

返回文件当前位置。

11

file.truncate([size])

从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后后面的所有字符被删除,其中 windows 系统下的换行代表2个字符大小。

12

file.write(str)

将字符串写入文件,返回的是写入的字符长度。

13

file.writelines(sequence)

向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。


本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!

链接: https://fly63.com/course/36_2101

目录选择