简体   繁体   中英

how to sequentially read two txt files and write into a new file in python?

I have two txt files, with 100000 lines for each file, now I need to generate a new file which combines the content from previous two txt files in such a way that, every 32 lines in the first file and every 64 lines in the second file are extracted and then write into the new file, so on and so on until all the lines in the both files are writen into the new file.

How would I do it in python, I know the way of reading all the lines in one file and write them into another.

with open(app_path+'/empty.txt','r') as source:
    data = [  (random.random(), line) for line in source ]
    data.sort()
with open(app_path+'/empty2.txt','w') as target:
    for _,line in data:
        target.write( line )

but for reading 2 files, extracting the content and writing sequentially, I have no idea

As per TessellatingHeckler, you will run out of file 2 first. This method will then continue to write from the remaining file until done.

from itertools import islice
with open('target.txt', 'w') as target:
    f1, f2 = open('f1.txt'), open('f2.txt')
    while True:
        ls1 = islice(f1, 32)
        if not ls1:
            # will not happen in this case
            target.write('\n' + f2.read())
            break
        ls2 = islice(f2, 64)
        if not ls2:
            target.write('\n' + f1.read())
            break
        target.write('\n'.join('\n'.join(ls) for ls in [ls1, ls2]))
    f1.close()
    f2.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM