How can I split a file in python?

前端 未结 9 639
失恋的感觉
失恋的感觉 2020-12-03 07:29

Is it possible to split a file? For example you have huge wordlist, I want to split it so that it becomes more than one file. How is this possible?

9条回答
  •  清歌不尽
    2020-12-03 07:59

    This is a late answer, but a new question was linked here and none of the answers mentioned itertools.groupby.

    Assuming you have a (huge) file file.txt that you want to split in chunks of MAXLINES lines file_part1.txt, ..., file_partn.txt, you could do:

    with open(file.txt) as fdin:
        for i, sub in itertools.groupby(enumerate(fdin), lambda x: 1 + x[0]//3):
            fdout = open("file_part{}.txt".format(i))
            for _, line in sub:
                fdout.write(line)
    

提交回复
热议问题