Python案例怎么读写本地TXT文件?

wen python案例 9

本文目录导读:

Python案例怎么读写本地TXT文件?

  1. 基本读写操作
  2. 实用案例
  3. 常用文件操作函数
  4. 注意事项

我来为您介绍Python读写本地TXT文件的几种常用方法。

基本读写操作

写入文件(三种模式)

# 方法1:覆盖写入(w模式)- 会清空原有内容
with open('example.txt', 'w', encoding='utf-8') as f:
    f.write('这是第一行内容\n')
    f.write('这是第二行内容\n')
# 方法2:追加写入(a模式)- 在文件末尾添加内容
with open('example.txt', 'a', encoding='utf-8') as f:
    f.write('这是追加的内容\n')
# 方法3:写入多行(writelines)
lines = ['行1\n', '行2\n', '行3\n']
with open('example.txt', 'w', encoding='utf-8') as f:
    f.writelines(lines)
print("文件写入完成!")

读取文件

# 方法1:一次性读取所有内容
with open('example.txt', 'r', encoding='utf-8') as f:
    content = f.read()
    print("完整内容:")
    print(content)
# 方法2:逐行读取(适合大文件)
print("\n逐行读取:")
with open('example.txt', 'r', encoding='utf-8') as f:
    for line in f:
        # 去除行尾的换行符
        print(line.strip())
# 方法3:读取所有行到列表
print("\n读取到列表:")
with open('example.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    for i, line in enumerate(lines, 1):
        print(f"第{i}行: {line.strip()}")

实用案例

案例1:文件复制

def copy_file(source, destination):
    """复制文件内容到新文件"""
    try:
        with open(source, 'r', encoding='utf-8') as src:
            content = src.read()
        with open(destination, 'w', encoding='utf-8') as dst:
            dst.write(content)
        print(f"成功将 {source} 复制到 {destination}")
    except FileNotFoundError:
        print(f"源文件 {source} 不存在")
    except Exception as e:
        print(f"复制过程中出错: {e}")
# 使用示例
copy_file('example.txt', 'backup.txt')

案例2:统计文本信息

def analyze_text(filename):
    """统计文件中的字符数、单词数和行数"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            content = f.read()
            chars = len(content)
            words = len(content.split())
            lines = content.count('\n') + 1
            print(f"文件: {filename}")
            print(f"字符数: {chars}")
            print(f"单词数: {words}")
            print(f"行数: {lines}")
    except FileNotFoundError:
        print(f"文件 {filename} 不存在")
# 使用示例
analyze_text('example.txt')

案例3:搜索和替换

def search_replace(filename, search_word, replace_word):
    """在文件中搜索并替换特定内容"""
    try:
        # 读取原文件内容
        with open(filename, 'r', encoding='utf-8') as f:
            content = f.read()
        # 执行替换
        new_content = content.replace(search_word, replace_word)
        # 写回文件
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(new_content)
        count = content.count(search_word)
        print(f"已将 {count} 处 '{search_word}' 替换为 '{replace_word}'")
    except FileNotFoundError:
        print(f"文件 {filename} 不存在")
# 使用示例
search_replace('example.txt', '内容', '数据')

案例4:读写配置文件

def save_config(config_dict, filename='config.txt'):
    """保存配置到文件"""
    with open(filename, 'w', encoding='utf-8') as f:
        for key, value in config_dict.items():
            f.write(f"{key}={value}\n")
    print(f"配置已保存到 {filename}")
def load_config(filename='config.txt'):
    """从文件读取配置"""
    config_dict = {}
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if '=' in line:
                    key, value = line.split('=', 1)
                    config_dict[key.strip()] = value.strip()
        return config_dict
    except FileNotFoundError:
        print(f"配置文件 {filename} 不存在")
        return {}
# 使用示例
# 保存配置
config = {
    'username': 'admin',
    'password': '123456',
    'port': '8080'
}
save_config(config)
# 读取配置
loaded_config = load_config()
print("读取的配置:", loaded_config)

常用文件操作函数

import os
# 检查文件是否存在
if os.path.exists('example.txt'):
    print("文件存在")
# 获取文件大小
size = os.path.getsize('example.txt')
print(f"文件大小: {size} 字节")
# 删除文件
os.remove('temporary.txt')
# 重命名文件
os.rename('old_name.txt', 'new_name.txt')
# 列出当前目录下的所有txt文件
txt_files = [f for f in os.listdir('.') if f.endswith('.txt')]
print("TXT文件列表:", txt_files)

注意事项

  1. 编码问题:始终使用 encoding='utf-8' 处理中文文件
  2. 使用with语句:自动管理文件打开和关闭
  3. 异常处理:使用try-except处理文件不存在等错误
  4. 大文件处理:对于大文件,使用逐行读取而非一次性读取

这些案例涵盖了Python读写TXT文件的主要场景,您可以根据实际需求选择合适的方法。

抱歉,评论功能暂时关闭!