假设我有一个48222行的文件。然后我给出一个索引值,比如21000
在Python中是否有任何方法可以从索引21000开始“移动”文件的内容,这样我就有了两个文件:原始文件和新文件。但原来的有21000行,新的有27222行
我读了这篇post,它使用了分区,并且很好地描述了我想要的:
with open("inputfile") as f:
contents1, sentinel, contents2 = f.read().partition("Sentinel text\n")
with open("outputfile1", "w") as f:
f.write(contents1)
with open("outputfile2", "w") as f:
f.write(contents2)
除了(1)它使用“Sentinel Text”作为分隔符,(2)它创建两个新文件并要求我删除旧文件。到目前为止,我是这样做的:
for r in result.keys(): #the filenames are in my dictionary, don't bother that
f = open(r)
lines = f.readlines()
f.close()
with open("outputfile1.txt", "w") as fn:
for line in lines[0:21000]:
#write each line
with open("outputfile2.txt", "w") as fn:
for line in lines[21000:]:
#write each line
这是一个相当手工的工作。有没有一个内置的或更有效的方法
还可以使用writelines()将从0到20999的行的切片列表转储到一个文件中,并将从21000到结尾的另一个切片列表转储到另一个文件中
相关问题 更多 >
编程相关推荐