Python创建新文件并复制现有文件内容及TypeError报错处理问询
报错原因
- 错误的核心是对
open()方法的传参逻辑理解有误:open()接收的第一个参数是文件路径字符串/Path对象,你的代码中file = open(new_file, "w")返回的是TextIOWrapper类型的文件句柄对象,将这个对象传入下一行的open(file, "r+")自然触发类型不匹配错误。 - 提前执行
open(new_file, "w")没有手动关闭文件,存在资源泄漏问题,即便目标文件预先存在时能正常运行,也属于不规范写法。 r+模式要求目标文件必须已存在,当目标文件不存在时直接用r+打开会报错,这就是你在函数内新建文件时触发异常的根本原因。
问题修复
直接删除冗余的file = open(new_file, "w")行,兼容目标文件不存在的场景即可,修复后的基础实现如下:
import os def copy_In(old_file, new_file): # 兼容目标文件不存在的场景,不存在则先创建空文件 if not os.path.exists(new_file): open(new_file, 'w').close() with open(new_file, "r+", encoding="utf-8") as f2: # 跳过前10行 for _ in range(10): line = f2.readline() # 如果文件不足10行,读到末尾就停止 if not line: break pos = f2.tell() # 读取10行之后的剩余内容 remainder = f2.read() f2.seek(pos) # 写入源文件内容 with open(old_file, "r", encoding="utf-8") as f1: f2.write(f1.read()) # 写入原剩余内容 f2.write(remainder)
更高效的实现方案
如果处理的是GB级大文件,将剩余内容全部读入内存会占用过高资源,更稳妥的方案是通过临时文件中转,避免内存占用过高,同时保证异常情况下原文件不会损坏:
import os import shutil from tempfile import NamedTemporaryFile def copy_In_efficient(old_file, new_file, insert_line=10): # 目标文件不存在直接复制源文件即可 if not os.path.exists(new_file): shutil.copy(old_file, new_file) return # 创建临时文件做中转 with NamedTemporaryFile(mode='w', encoding='utf-8', delete=False) as tmp_f, \ open(new_file, 'r', encoding='utf-8') as f2, \ open(old_file, 'r', encoding='utf-8') as f1: # 先写前insert_line行 for line_num, line in enumerate(f2, 1): tmp_f.write(line) if line_num == insert_line: break # 写入源文件全部内容 shutil.copyfileobj(f1, tmp_f) # 写入原文件剩余内容 shutil.copyfileobj(f2, tmp_f) # 用临时文件替换原目标文件 shutil.copystat(new_file, tmp_f.name) os.replace(tmp_f.name, new_file)
内容的提问来源于stack exchange,提问作者Zemelon
相关产品推荐
相关产品推荐

