Python:为什么一个文件在读取并写入另一个文件后为空? [英] Python: Why a file is empty after reading it and writing to another one?
问题描述
我对 Python 非常陌生.我想处理现有文件 (exist_file
),此外,还要创建它的副本.问题是,当我创建文件副本时,exist_file
变为空.
I am very new to Python.
I would like to work on an existing file (exist_file
) and, in addition, to create a copy of it. The problem is, when I create the copy of the file, the exist_file
becomes empty.
我的代码:
exist_file = open('some_pass/my_file.txt', 'r')
print exist_file.read() # Here the file is successfully printed
copy_of_file = open('new_copied_file.txt', 'w')
copy_of_file.write(exist_file.read())
print exist_file.read() # Here the file is empty
为什么 exist_file
是空的?感谢您的帮助
Why exist_file
is empty? Thank you for your help
推荐答案
如Python 文档的第一个示例,当您对文件调用 read()
两次而不调用 .seek(0)
时>,第二次调用返回一个空字符串.
As shown in the first example of the Python documentation, when you call read()
twice on a file without calling a .seek(0)
, the second call returns an empty string.
解决此问题的最佳方法是将第一次调用的结果保存在变量中.
The best way to fix this is to keep the result of the first call in a variable.
这篇关于Python:为什么一个文件在读取并写入另一个文件后为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!