gpt4 book ai didi

Python - 将数据从一个文件复制到另一个文件

转载 作者:行者123 更新时间:2023-11-30 22:12:47 26 4
gpt4 key购买 nike

我正在尝试将一个文件的内容复制到另一个文件。

脚本成功地将内容复制到文件,但是当我尝试运行 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

关于Python - 将数据从一个文件复制到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50989402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com