假设我有一个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)它使用“哨兵文本”作为分隔符之外,(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
这是一项相当手工的工作。有没有一个内置的或更有效的方法?
发布于 2016-02-29 23:15:30
您还可以使用写线(),并将从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)
https://stackoverflow.com/questions/35716223
复制