You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python读取文本文件前3行写入新文件,并验证写入内容

解决方案:读取文件前三行并写入新文件后验证内容

实现思路

  • 读取源文件file_in.txt的前三行内容
  • 将读取到的内容写入新文件file_out.txt
  • 读取目标文件并打印内容,验证操作结果

Python 代码实现

基础版本(假设文件至少有三行)

# 读取源文件前三行
with open('file_in.txt', 'r', encoding='utf-8') as in_file:
    first_three_lines = [next(in_file) for _ in range(3)]

# 写入目标文件
with open('file_out.txt', 'w', encoding='utf-8') as out_file:
    out_file.writelines(first_three_lines)

# 读取并打印目标文件内容
with open('file_out.txt', 'r', encoding='utf-8') as out_file:
    print("file_out.txt 内容:")
    print(out_file.read())

健壮版本(兼容文件不足三行的情况)

如果file_in.txt可能少于三行,用以下代码避免抛出异常:

# 读取源文件前三行(最多三行)
first_three_lines = []
with open('file_in.txt', 'r', encoding='utf-8') as in_file:
    for line in in_file:
        first_three_lines.append(line)
        if len(first_three_lines) == 3:
            break

# 写入目标文件
with open('file_out.txt', 'w', encoding='utf-8') as out_file:
    out_file.writelines(first_three_lines)

# 读取并打印目标文件内容
with open('file_out.txt', 'r', encoding='utf-8') as out_file:
    print("file_out.txt 内容:")
    print(out_file.read())

关键说明

  • 使用with语句处理文件操作,会自动关闭文件,避免资源泄漏
  • 指定encoding='utf-8'确保跨平台编码一致性,若文件使用其他编码(如GBK),需对应修改
  • 写入模式'w'会覆盖file_out.txt原有内容,若需保留原有内容并追加,可改为'a'模式
  • 若文件不在当前工作目录,需传入完整文件路径(例如C:/docs/file_in.txt或/home/user/file_in.txt)

内容的提问来源于stack exchange,提问作者Pasindu Vishmika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 13:10:24