我对 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是空的?
如Python 文档中的此示例所示,当您read()对一个文件调用两次而不调用 a时.seek(0),第二次调用将返回一个空字符串。
解决此问题的最佳方法是将第一次调用的结果保存在变量中。