Ian
Ian

Reputation: 30823

"Move" some parts of the file to another file

Let say I have a file with 48,222 lines. I then give an index value, let say, 21,000.

Is there any way in Python to "move" the contents of the file starting from index 21,000 such that now I have two files: the original one and the new one. But the original one now is having 21,000 lines and the new one 27,222 lines.

I read this post which uses partition and is quite describing what I want:

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)

Except that (1) it uses "Sentinel Text" as separator, (2) it creates two new files and require me to delete the old file. As of now, the way I do it is like this:

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                   

Which is quite a manual work. Is there a built-in or more efficient way?

Upvotes: 0

Views: 302

Answers (1)

YBathia
YBathia

Reputation: 902

You can also use writelines() and dump the sliced list of lines from 0 to 20999 into one file and another sliced list from 21000 to the end into another file.

   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)

Upvotes: 1

Related Questions