为什么文件读取后是空的?

Hal*_*ona 5 python file

我对 Python 很陌生。我想处理现有文件 ( exist_file),并创建它的副本。问题是,当我创建文件的副本时,它exist_file变成空的。

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
Run Code Online (Sandbox Code Playgroud)

为什么exist_file是空的?

Phy*_*sis 7

如Python 文档中的此示例所示,当您read()对一个文件调用两次而不调用 a时.seek(0),第二次调用将返回一个空字符串。

解决此问题的最佳方法是将第一次调用的结果保存在变量中。

  • 另外,请确保在写入文件后关闭文件(或使用 [`with` 语句](http://docs.python.org/2/reference/compound_stmts.html#the-with-statement)),否则Python 可能需要一段时间才能决定为您关闭它。 (2认同)