当前位置: 代码网 > it编程>前端脚本>Python > Python文件操作入门:新手如何快速掌握文件读写技巧

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

2026年09月11日 Python 我要评论
1. python io操作入门指南刚接触python编程的新手常常会对文件操作感到困惑。io(input/output)操作是编程中最基础也最重要的技能之一,它让程序能够与外部世界进行数据交换。py

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()
    # 文件会在代码块结束后自动关闭

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

  • 'r':只读(默认)
  • 'w':写入(会覆盖现有文件)
  • 'a':追加
  • 'b':二进制模式
  • '+':读写模式

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文件操作内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com