How can I split a file in python?

前端 未结 9 612
失恋的感觉
失恋的感觉 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 08:14

    A better loop for sli's example, not hogging memory :

    splitLen = 20         # 20 lines per file
    outputBase = 'output' # output.1.txt, output.2.txt, etc.
    
    input = open('input.txt', 'r')
    
    count = 0
    at = 0
    dest = None
    for line in input:
        if count % splitLen == 0:
            if dest: dest.close()
            dest = open(outputBase + str(at) + '.txt', 'w')
            at += 1
        dest.write(line)
        count += 1
    

提交回复
热议问题