Python复制文件后打印新文件内容却得到字符数的问题求助
问题:复制文件函数中打印新文件变量得到字符数而非内容
我写了一个复制源文件内容到新文件的函数,它接收源文件路径和目标文件路径两个参数。打印源文件内容时能得到预期的文件内容,但打印新文件相关变量时却返回文件的字符数(这次是14)。我搞不懂为什么逻辑相似的代码会有不同输出,附上代码和输出结果,求技术帮助。
代码
# 创建待复制的文件: with open(source_link, 'w') as f: f.write('Copy this file') # 复制函数: def copy_file_content(source, destination): # 读取源文件内容: f1 = open(source, 'r') copied_file = f1.read() f1.close() # 将内容写入新文件: f2 = open(destination, 'w') new_file = f2.write(copied_file) f2.close # 打印源文件内容: print(copied_file) print('***') # 打印新文件相关变量: print(new_file) copy_file_content(source = source_link, destination = dest_link)
输出
Copy this file *** 14
问题原因与解决方法
- 核心原因:
f2.write()方法的返回值是写入的字符数量,而不是写入的内容。你把这个返回值赋值给了new_file变量,所以打印它会得到14(刚好是Copy this file的字符数)。 - 代码还有个小疏漏:
f2.close少了括号,应该写成f2.close(),否则文件不会被正确关闭,可能导致内容没有完全写入磁盘。 - 如果想打印新文件的内容,需要重新打开目标文件读取内容:
在函数中添加读取逻辑即可:# 读取新文件内容并打印 f3 = open(destination, 'r') new_file_content = f3.read() f3.close() print(new_file_content) - 更稳妥的写法是使用
with语句自动管理文件,不用手动调用close(),避免遗漏:
修改后的完整函数示例:def copy_file_content(source, destination): # 读取源文件 with open(source, 'r') as f1: copied_file = f1.read() # 写入目标文件 with open(destination, 'w') as f2: f2.write(copied_file) # 打印源文件内容 print(copied_file) print('***') # 读取并打印目标文件内容 with open(destination, 'r') as f3: new_file_content = f3.read() print(new_file_content)
内容的提问来源于stack exchange,提问作者Hadas Yonat
相关产品推荐
相关产品推荐

