位置: 文档库 > Python > 文档下载预览

《Python基础:文件读写 .doc》

1. 下载的文档为doc格式,下载后可用word或者wps进行编辑;

2. 将本文以doc文档格式下载到电脑,方便收藏和打印;

3. 下载后的文档,内容与下面显示的完全一致,下载之前请确认下面内容是否您想要的,是否完整.

点击下载文档

Python基础:文件读写 .doc

《Python基础:文件读写》

在Python编程中,文件读写是核心技能之一。无论是处理日志文件、读取配置信息,还是生成报表数据,文件操作都贯穿于各类应用场景。本文将系统讲解Python文件读写的基础知识,涵盖文件打开模式、读写方法、异常处理及实际应用案例,帮助读者快速掌握这一关键技能。

一、文件操作基础

Python通过内置的open()函数实现文件操作。该函数接受两个主要参数:文件路径和打开模式,返回一个文件对象,通过该对象可进行读写操作。

# 基本文件打开示例
file = open('example.txt', 'r')  # 以只读模式打开文件
content = file.read()  # 读取全部内容
file.close()  # 关闭文件

上述代码存在两个问题:未处理文件不存在的情况,且未使用with语句自动关闭文件。改进后的代码如下:

try:
    with open('example.txt', 'r') as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("文件不存在")

1.1 文件打开模式

Python支持多种文件打开模式,常用模式如下:

模式 描述
'r' 只读模式(默认),文件必须存在
'w' 写入模式,覆盖原有内容
'a' 追加模式,在文件末尾添加内容
'x' 独占创建模式,文件已存在则报错
'b' 二进制模式(如'rb'、'wb')
'+' 读写模式(如'r+'、'w+')

组合使用示例:

# 读写模式打开文件
with open('data.txt', 'r+') as file:
    content = file.read()
    file.write('\n新增内容')

二、文件读取方法

文件对象提供多种读取方法,适用于不同场景:

2.1 read()方法

读取整个文件内容,返回字符串(文本模式)或字节对象(二进制模式)。

with open('large_file.txt', 'r') as file:
    full_content = file.read()  # 慎用大文件

可指定读取字符数:

with open('file.txt', 'r') as file:
    first_100 = file.read(100)  # 读取前100个字符

2.2 readline()方法

逐行读取文件,返回单行字符串。

with open('lines.txt', 'r') as file:
    line1 = file.readline()  # 读取第一行
    line2 = file.readline()  # 读取第二行

2.3 readlines()方法

读取所有行,返回包含各行字符串的列表。

with open('multi_line.txt', 'r') as file:
    lines = file.readlines()  # ['第一行\n', '第二行\n']
    for line in lines:
        print(line.strip())  # 去除换行符

2.4 迭代文件对象

更高效的方式是直接迭代文件对象:

with open('big_file.txt', 'r') as file:
    for line in file:  # 逐行迭代,内存友好
        print(line.rstrip())

三、文件写入方法

写入操作主要使用write()方法,需注意不同模式的区别:

3.1 写入文本

# 覆盖写入
with open('output.txt', 'w') as file:
    file.write('第一行内容\n')
    file.write('第二行内容\n')

# 追加写入
with open('output.txt', 'a') as file:
    file.write('追加的内容\n')

3.2 写入多行

使用writelines()方法写入列表:

lines = ['第一行\n', '第二行\n', '第三行\n']
with open('multi_output.txt', 'w') as file:
    file.writelines(lines)

3.3 二进制文件操作

处理图片等二进制文件时需使用'b'模式:

# 复制二进制文件
with open('source.jpg', 'rb') as src:
    data = src.read()
with open('copy.jpg', 'wb') as dst:
    dst.write(data)

四、文件定位操作

文件对象提供seek()tell()方法控制读写位置:

with open('position.txt', 'r+') as file:
    file.write('0123456789')
    file.seek(0)  # 移动到文件开头
    print(file.read(5))  # 输出'01234'
    file.seek(3)
    file.write('ABC')  # 修改第4个字符开始的内容

五、上下文管理器

使用with语句可自动管理文件资源:

# 自动关闭文件
with open('auto_close.txt', 'w') as file:
    file.write('自动关闭示例')
# 此处文件已自动关闭

自定义上下文管理器示例:

class CustomFile:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
    
    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()

# 使用自定义上下文管理器
with CustomFile('custom.txt', 'w') as f:
    f.write('自定义上下文示例')

六、实际应用案例

6.1 日志文件分析

def analyze_logs(log_file):
    error_count = 0
    with open(log_file, 'r') as file:
        for line in file:
            if 'ERROR' in line:
                error_count += 1
    return error_count

print(f"发现{analyze_logs('app.log')}个错误")

6.2 CSV文件处理

虽然Python有csv模块,但基础文件操作也可处理简单CSV:

def write_csv(data, filename):
    with open(filename, 'w') as file:
        for row in data:
            file.write(','.join(map(str, row)) + '\n')

data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
write_csv(data, 'data.csv')

6.3 配置文件读写

def read_config(filename):
    config = {}
    with open(filename, 'r') as file:
        for line in file:
            if '=' in line:
                key, value = line.split('=', 1)
                config[key.strip()] = value.strip()
    return config

def write_config(config, filename):
    with open(filename, 'w') as file:
        for key, value in config.items():
            file.write(f"{key}={value}\n")

config = {'host': 'localhost', 'port': '8080'}
write_config(config, 'config.ini')
print(read_config('config.ini'))

七、常见问题与解决方案

7.1 编码问题

处理非ASCII文件时需指定编码:

# 读取UTF-8文件
with open('chinese.txt', 'r', encoding='utf-8') as file:
    print(file.read())

# 处理编码错误
try:
    with open('invalid.txt', 'r', encoding='utf-8') as file:
        content = file.read()
except UnicodeDecodeError:
    with open('invalid.txt', 'r', encoding='gbk') as file:
        content = file.read()

7.2 大文件处理

分块读取大文件:

def read_large_file(filename, chunk_size=1024):
    with open(filename, 'r') as file:
        while True:
            chunk = file.read(chunk_size)
            if not chunk:
                break
            yield chunk

for chunk in read_large_file('huge.txt'):
    process(chunk)  # 处理每个数据块

7.3 路径处理

使用os.path模块处理跨平台路径:

import os

file_path = os.path.join('folder', 'subfolder', 'file.txt')
print(os.path.abspath(file_path))  # 获取绝对路径

八、性能优化建议

1. 批量写入优于多次单行写入

2. 大文件使用迭代器而非read()

3. 二进制模式处理非文本文件

4. 合理使用缓冲区(通过buffering参数)

九、总结

Python文件读写提供了灵活的操作方式,掌握基础模式和方法后,可应对绝大多数文件处理场景。实际应用中需注意异常处理、资源管理和编码问题,对于复杂需求可结合标准库模块(如csvjson)或第三方库(如pandas)实现更高效的处理。

关键词:Python文件操作、open函数、文件读写模式、上下文管理器、文件定位、二进制文件、编码处理、大文件处理

简介:本文系统讲解Python文件读写的基础知识,涵盖文件打开模式、读写方法、异常处理、上下文管理器使用及实际应用案例,包含编码处理、大文件分块读取等高级技巧,适合Python初学者和需要巩固文件操作基础的开发者。

《Python基础:文件读写 .doc》
将本文以doc文档格式下载到电脑,方便收藏和打印
推荐度:
点击下载文档