python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python文件操作

Python文件操作入门:新手如何快速掌握文件读写技巧

作者:菩提风

还在为Python文件操作发愁吗,本文从零开始带你掌握IO操作核心技能,包括文件读写、路径处理、CSV和JSON文件操作,以及高级技巧和性能优化,最后通过实战项目巩固知识,让你轻松应对各种文件处理场景

1. Python IO操作入门指南

刚接触Python编程的新手常常会对文件操作感到困惑。IO(Input/Output)操作是编程中最基础也最重要的技能之一,它让程序能够与外部世界进行数据交换。Python提供了简洁而强大的IO处理能力,特别适合初学者掌握。

提示:本文所有代码示例均基于Python 3.x版本,与Python 2.x有重要语法区别

文件操作主要分为文本模式和二进制模式。文本模式会自动处理编码转换,而二进制模式则直接操作字节数据。新手建议先从文本模式开始学习,等基础扎实后再接触二进制操作。

2. 文件读写基础操作

2.1 打开和关闭文件

Python使用内置的open()函数来打开文件,基本语法如下:

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

更安全的做法是使用with语句,它可以自动处理文件的关闭:

with open('example.txt', 'r') as file:
    content = file.read()
    # 文件会在代码块结束后自动关闭

常见的文件打开模式包括:

2.2 读取文件内容

Python提供了多种读取文件内容的方法:

# 读取整个文件
with open('example.txt', 'r') as file:
    content = file.read()

# 逐行读取
with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())  # strip()去除行尾换行符

# 读取所有行到列表
with open('example.txt', 'r') as file:
    lines = file.readlines()

注意:处理大文件时,避免使用read()或readlines()一次性读取全部内容,这可能导致内存不足。应该使用逐行读取或指定读取大小。

2.3 写入文件内容

写入文件同样简单:

# 写入新文件(会覆盖已有内容)
with open('output.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.")

# 追加内容到已有文件
with open('output.txt', 'a') as file:
    file.write("\nAppended content.")

3. 文件路径处理

3.1 相对路径与绝对路径

Python支持相对路径和绝对路径:

import os

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

# 组合路径(跨平台安全)
file_path = os.path.join('data', 'example.txt')

# 检查路径是否存在
if os.path.exists(file_path):
    print("文件存在")

3.2 Path对象(Python 3.4+)

pathlib模块提供了更面向对象的路径操作方式:

from pathlib import Path

# 创建Path对象
file_path = Path('data') / 'example.txt'

# 检查文件
if file_path.exists():
    content = file_path.read_text()
    file_path.write_text("New content")

4. 常见IO操作场景

4.1 配置文件读写

JSON格式是常用的配置文件格式:

import json

# 写入JSON文件
config = {'name': 'Alice', 'age': 25, 'active': True}
with open('config.json', 'w') as file:
    json.dump(config, file, indent=4)

# 读取JSON文件
with open('config.json', 'r') as file:
    loaded_config = json.load(file)

4.2 CSV文件处理

使用csv模块处理表格数据:

import csv

# 写入CSV文件
with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['Alice', 25, 'New York'])
    writer.writerow(['Bob', 30, 'London'])

# 读取CSV文件
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

4.3 日志文件记录

实现简单的日志记录功能:

import logging

logging.basicConfig(
    filename='app.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

logging.info('程序启动')
try:
    result = 10 / 0
except ZeroDivisionError:
    logging.error('除零错误', exc_info=True)

5. 高级IO技巧

5.1 上下文管理器进阶

可以自定义上下文管理器来处理特殊资源:

class DatabaseConnection:
    def __enter__(self):
        print("连接数据库")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("关闭数据库连接")
        if exc_type:
            print(f"发生错误: {exc_val}")

with DatabaseConnection() as db:
    print("执行数据库操作")
    # raise Exception("模拟错误")

5.2 内存文件操作

使用io模块在内存中操作文件:

import io

# 内存中的文本文件
text_buffer = io.StringIO()
text_buffer.write("Hello, ")
text_buffer.write("World!")
content = text_buffer.getvalue()
print(content)
text_buffer.close()

# 内存中的二进制文件
binary_buffer = io.BytesIO()
binary_buffer.write(b'\x01\x02\x03')
binary_content = binary_buffer.getvalue()
print(binary_content)
binary_buffer.close()

5.3 文件压缩处理

使用gzip或zipfile模块处理压缩文件:

import gzip
import zipfile

# 读写gzip文件
with gzip.open('example.gz', 'wt') as f:
    f.write("压缩的文本内容")

# 创建ZIP文件
with zipfile.ZipFile('archive.zip', 'w') as zipf:
    zipf.write('example.txt')
    
# 读取ZIP文件
with zipfile.ZipFile('archive.zip', 'r') as zipf:
    zipf.extractall('extracted')

6. 性能优化与错误处理

6.1 缓冲与批量操作

对于大文件或性能敏感场景,合理使用缓冲:

# 设置缓冲区大小(字节)
with open('large_file.txt', 'r', buffering=8192) as f:
    while True:
        chunk = f.read(4096)  # 每次读取4KB
        if not chunk:
            break
        process(chunk)

6.2 异常处理

完善的错误处理是健壮IO操作的关键:

try:
    with open('missing_file.txt', 'r') as f:
        content = f.read()
except FileNotFoundError:
    print("文件不存在")
except PermissionError:
    print("没有访问权限")
except IOError as e:
    print(f"IO错误: {e}")
except Exception as e:
    print(f"未知错误: {e}")
else:
    print("文件读取成功")
finally:
    print("操作完成")

6.3 文件锁

多进程/线程环境下可能需要文件锁:

import fcntl

with open('shared_file.txt', 'a') as f:
    try:
        fcntl.flock(f, fcntl.LOCK_EX)  # 获取排他锁
        f.write("独占写入的内容\n")
    finally:
        fcntl.flock(f, fcntl.LOCK_UN)  # 释放锁

7. 实战项目:简易日记本程序

结合所学知识,实现一个命令行日记本:

import json
from pathlib import Path
from datetime import datetime

DIARY_FILE = 'my_diary.json'

def load_diary():
    try:
        with open(DIARY_FILE, 'r') as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        return []

def save_diary(entries):
    with open(DIARY_FILE, 'w') as f:
        json.dump(entries, f, indent=2)

def add_entry():
    entries = load_diary()
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    content = input("写下今天的日记: ")
    entries.append({'time': timestamp, 'content': content})
    save_diary(entries)
    print("日记已保存!")

def list_entries():
    entries = load_diary()
    for idx, entry in enumerate(entries, 1):
        print(f"{idx}. [{entry['time']}] {entry['content']}")

def main():
    while True:
        print("\n简易日记本")
        print("1. 写日记")
        print("2. 看日记")
        print("3. 退出")
        choice = input("请选择: ")
        
        if choice == '1':
            add_entry()
        elif choice == '2':
            list_entries()
        elif choice == '3':
            break
        else:
            print("无效选择")

if __name__ == '__main__':
    main()

这个程序涵盖了文件读写、JSON序列化、异常处理等核心IO操作,是很好的综合练习项目。

到此这篇关于Python文件操作入门:新手如何快速掌握文件读写技巧的文章就介绍到这了,更多相关Python文件操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文