Python 文件及 IO 操作

一、概述

文件操作是编程中的基本任务之一,用于读取、写入和管理文件内容。Python 提供了强大的文件操作功能,通过内置的 open 函数和相关方法,可以轻松地进行文件的读写操作。

二、文件操作的基本步骤

文件操作通常包括以下步骤:

  1. 打开文件

  2. 读取或写入文件

  3. 关闭文件

1. 打开文件

使用 open 函数打开文件,其基本语法如下:

file = open(file_path, mode='r', encoding=None)
  • file_path:文件的路径,可以是相对路径或绝对路径。

  • mode:文件打开模式,默认为 'r'(只读模式)。常见的模式有:

    • 'r':只读模式,文件必须存在。

    • 'w':写入模式,如果文件存在则覆盖,不存在则创建。

    • 'a':追加模式,如果文件存在则在文件末尾追加内容,不存在则创建。

    • 'r+':读写模式,文件必须存在。

    • 'b':二进制模式,用于处理二进制文件(如图片)。

    • 'rb': 只读方式打开二进制文件

    • 'wb': 覆盖写模式写入二进制文件

  • encoding:指定文件的编码格式,如 'utf-8'

2. 读取文件

打开文件后,可以使用以下方法读取文件内容:

  • read():读取整个文件内容为一个字符串。

  • read(size):从文件夹中读取size个字符或字节,没有给定读取全部内容

  • readline():读取文件的一行。

  • readlines():读取文件的所有行,返回一个列表,每行是一个元素。

示例:读取文件

# 打开文件
file = open('example.txt', 'r', encoding='utf-8')

# 读取整个文件内容
content = file.read()
print(content)

# 关闭文件
file.close()

3. 写入文件

写入文件时,需要指定写入模式(如 'w''a'),然后使用 write()writelines() 方法。

  • write():写入字符串内容。

  • writelines():写入一个字符串列表,每个字符串作为文件的一行。

示例:写入文件

# 打开文件(写入模式)
file = open('example.txt', 'w', encoding='utf-8')

# 写入内容
file.write("Hello, World!\n")
file.write("This is a test file.\n")

# 关闭文件
file.close()

4. 关闭文件

使用 close() 方法关闭文件,释放系统资源。这是一个重要的步骤,确保文件操作完成后释放资源。

三、使用 with 语句

  • 为了避免忘记关闭文件,Python 提供了 with 语句,又称上下文管理器,可以自动管理文件的打开和关闭。使用 with 语句可以使代码更加简洁和安全。

  • 语法结构:

    with open(...) as file
      pass
    

示例:使用 with 语句

# 写入文件
def write():
    with open('a.txt', 'w', encoding='utf-8') as file:
        file.write("Hello, World!\n")
        file.write("This is a test file.\n")

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

# 复制文件
def copy(src,dest):
    with open(src,'r',encoding='utf-8') as file:
        with open(dest,'w',encoding='utf-8') as file2:
            file2.write(file.read())

if __name__ == '__main__':
    write()
    read()
    copy('man.txt','../copy/man.txt')

四、文件操作的常用方法

1. 读取文件

  • 逐行读取:使用 for 循环逐行读取文件内容。

    with open('example.txt', 'r', encoding='utf-8') as file:
        for line in file:
            print(line.strip())  # 使用 strip() 去掉换行符
    
  • 读取指定行数:使用 readline()readlines()

    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()  # 读取所有行
        print(lines)
    

2. 写入文件

  • 追加内容:使用 'a' 模式追加内容。

    with open('example.txt', 'a', encoding='utf-8') as file:
        file.write("This is a new line.\n")
    
  • 写入多行:使用 writelines() 写入多行内容。

    lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
    with open('example.txt', 'w', encoding='utf-8') as file:
        file.writelines(lines)
    

3. 文件指针操作

  • seek():移动文件指针到指定位置。

  • 英文占一个字节,中文gbk编码占两个字节,utf-8编码占三个字节

    with open('example.txt', 'r', encoding='utf-8') as file:
        file.seek(10)  # 移动指针到第10个字符
        content = file.read()
        print(content)
    
  • tell():获取当前文件指针的位置。

    with open('example.txt', 'r', encoding='utf-8') as file:
        print(file.tell())  # 输出当前指针位置
    

五、文件操作的注意事项

1. 文件路径

  • 相对路径:相对于当前工作目录的路径。

  • 绝对路径:从根目录开始的完整路径。

2. 文件编码

  • 在读写文件时,指定正确的编码格式非常重要,尤其是处理中文等非ASCII字符时。

  • 常用的编码格式有 'utf-8''gbk' 等。

3. 文件存在性检查

  • 在打开文件之前,可以使用 os.path.exists() 检查文件是否存在。

    import os
    
    file_path = 'example.txt'
    if os.path.exists(file_path):
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
            print(content)
    else:
        print("文件不存在")
    

4. 异常处理

  • 在文件操作中,可能会遇到各种异常(如文件不存在、权限不足等)。可以使用 try-except 块来捕获和处理这些异常。

    try:
        with open('example.txt', 'r', encoding='utf-8') as file:
            content = file.read()
            print(content)
    except FileNotFoundError:
        print("文件未找到")
    except Exception as e:
        print(f"发生错误:{e}")
    

六、实际应用示例

1. 读取日志文件

创建XX客服管理系统的登录界面,每次登录时,将用户的登录日志写入文件中,并且可以在程序中查看用户的登录日志

# 文件读取
log_file = 'log.txt'
with open(log_file, 'r', encoding='utf-8') as file:
    for line in file:
        print(line.strip())

# line.strip() 会将空行转换为一个空字符串

⭐-----⭐------⭐--------⭐---------⭐-----------⭐-----------⭐
import time
import os

# 日志文件路径
path = './log.txt'

def write_log(username, login_success):
    with open(path, 'a', encoding='utf-8') as file:
        logtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        if login_success:
            file.write(f'用户名{username}, 登录时间{logtime}, 登录成功\n')
        else:
            file.write(f'error! 用户名{username}, 登录时间{logtime}, 登录失败\n')

def read_log():
    with open(path, 'r', encoding='utf-8') as file:
        for line in file:
            print(line.strip())

def login():
    username = input('请输入用户名:')
    pwd = input('请输入密码:')
    return username, pwd

def show():
    print('输入0退出,输入1查看系统日志')

def main():
    while True:
        username, pwd = login()
        login_success = (username == 'admin' and pwd == '1')
        if not login_success:
            print('登录失败')
            write_log(username, False)
            a = input('是否重新登录 (Y/N):')
            if a not in ('y', 'Y'):
                break
        else:
            print('登录成功')
            write_log(username, True)
            break

    show()
    while True:
        try:
            a = int(input('请输入操作数字:'))
            if a == 0:
                break
            elif a == 1:
                read_log()
            else:
                print("无效的操作数字,请重新输入。")
        except ValueError:
            print("请输入一个有效的数字。")

if __name__ == '__main__':
    main()

2. 处理CSV文件

CSV文件是一种常见的数据文件格式,可以使用 csv 模块读取和写入CSV文件。

示例:读取CSV文件

import csv

csv_file = 'data.csv'
with open(csv_file, 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

示例:写入CSV文件

import csv

data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
csv_file = 'data.csv'
with open(csv_file, 'w', encoding='utf-8', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

3. 文件复制

可以使用文件操作实现文件的复制功能。

# 文件的复制

def copy_file(src,dest):
    # 打开文件
    file1 = open(src,"rb")  # 源文件
    file2 = open(dest,'wb') # 目标文件
    # 文件操作
    s = file1.read()
    file2.write(s)
    # 关闭文件 注意:先打开的后关闭,后打开的先关闭
    file2.close()
    file1.close()

if __name__ == '__main__':
    src = './logo.jpg'
    dest = '../copy/logo.jpg'  # 上一级目录
    copy_file(src,dest)
    print('文件复制完毕')
source_file = 'source.txt'
destination_file = 'destination.txt'

with open(source_file, 'r', encoding='utf-8') as src:
    content = src.read()

with open(destination_file, 'w', encoding='utf-8') as dest:
    dest.write(content)

4. 匹配文本

# 模拟淘宝客服自动回复
需求:淘宝客服为了快速回答买家问题,设置了自动回复的功能,当有买家咨询时,客服自助系统会首先使用提前规划好的内容进行回复请用Python程序实现这一功能

replay.txt:
订单|如果您有任何订单问题,可以登录淘宝账号,点击“我的订单",查看订单详情
物流|如果您有任何物流问题,可以登录淘宝账号,点击"我的订单",查看商品物流
账户|如果您有任何账户问题,可以联系淘宝客服,电话:XXXX-XXXXXX
支付|如果您有任何支付问题,可以联系支付宝客服,QQ:xxxxxxx
def find_answer(question):
    with open('replay.txt','r',encoding='utf-8') as file:
        while True:
            line = file.readline()
            if line == '':
                break
            keyword = line.split('|')[0]
            replay = line.split('|')[1]
            if keyword in question:
                return replay
    return False

if __name__ == '__main__':
    question=input('HI,XXX小好,小蜜在此等主人很久了,有什么烦恼和小蜜说说吧:')
    while True:
        if question=='bye':
            break #退出循环
        else:
            #开始查找要回复的答案
            replay=find_answer(question)
            if replay == False :#函数的返回值如果是False
                question=input('小蜜不知道你在说什么,您可以问我一些关于订单、物流、支付、账户方面的问题,退出请输入bye:')
            else:
                print(replay)
                question=input('小主,您还可以问一些关于订单、物流、支付、账户方面的问题,退出请输入bye:')
    print('小主再见')

posted @ 2025-04-19 18:22  kyle_7Qc  阅读(76)  评论(0)    收藏  举报