[英]Python - Copying data from one file to another file
我试图将一个文件的内容复制到另一个文件。
该脚本成功将内容复制到该文件,但是当我尝试使用输出文件运行READ
命令来打印输出时,它是空白的。
from sys import argv
script, inputFile, outputFile = argv
inFile = open(inputFile)
inData = inFile.read()
outFile = open(outputFile, 'w+')
outFile.write(inData)
print("The new data is:\n",outFile.read())
inFile.close()
outFile.close()
在write
操作之后,文件指针位于文件末尾,因此您需要将其重置为开头。 此外,文件系统IO缓冲区可能尚未在此时刷新(您尚未关闭文件)...
简单的解决方案:关闭outFile并重新打开以进行阅读。
作为旁注:始终确保在发生任何事情时关闭文件,特别是在写入时,否则您可能最终会损坏数据。 最简单的方法是with
语句:
with open(...) as infile, (...) as outfile:
outfile.write(infile.read())
# at this point both files have been automagically closed
outFile
之后你忘了回到outFile
的开头。 所以插入outFile.seek(0)
应该可以解决你的问题。
完成写入后,文件指针位于文件的末尾,因此没有数据存在。 重新定位指向文件开头的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.