我正在编写一个 python 程序来将一个文件逐行复制到一个新文件中。我的代码如下,其中我使用循环逐行复制文件。
然而,由于文件中的行数可能会发生变化,有没有一种方法可以在 python 中逐行复制文件而不使用依赖于数字的循环,而是依赖于诸如 EOF 字符之类的东西来终止循环?
import os
import sys
i = 0
f = open("C:\\Users\\jgr208\\Desktop\\research_12\\sap\\beam_springs.$2k","r")
copy = open("C:\\Users\\jgr208\\Desktop\\research_12\\sap\\copy.$2k","wt")
#loop that copies file line by line and terminates loop when i reaches 10
while i < 10:
line = f.readline()
copy.write(str(line))
i = i +1
f.close()
copy.close()
最佳答案
您可以通过遍历文件对象本身来遍历 Python 文件对象中的行:
for line in f:
copy.write(line)
An alternative approach to reading lines is to loop over the file object. This is memory efficient, fast, and leads to simpler code:
>>> for line in f:
print line,
关于python - 在python中逐行复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11584300/