假设我有一个48,222行的文件。然后我给出一个索引值,比方说21,000。
Python中是否有任何方法可以从索引21,000开始“移动”文件内容,这样现在我有两个文件:原始文件和新文件。但是原来现在有21,000行,新的有27,222行。
我读了这个使用分区的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
这是一项非常手工的工作。是否有内置或更有效的方式?
答案 0 :(得分:1)
您还可以使用writelines()并将切片的0到20999行列表转储到一个文件中,将另一个切片列表从21000转储到另一个文件。
with open("inputfile") as f:
content = f.readlines()
content1 = content[:21000]
content2 = content[21000:]
with open("outputfile1.txt", "w") as fn1:
fn1.writelines(content1)
with open('outputfile2.txt','w') as fn2:
fn2.writelines(content2)