“移动”文件的某些部分到另一个fi

2024-05-23 19:49:59 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个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                   

这是一个相当手工的工作。有没有一个内置的或更有效的方法


Tags: 文件方法inforaswithlineopen
1条回答
网友
1楼 · 发布于 2024-05-23 19:49:59

还可以使用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)

相关问题 更多 >