How can I split a file in python?

前端 未结 9 615
失恋的感觉
失恋的感觉 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:17

    All the provided answers are good and (probably) work However, they need to load the file into memory (as a whole or partially). We know Python is not very efficient in this kind of tasks (or at least is not as efficient as the OS level commands).

    I found the following is the most efficient way to do it:

    import os
    
    MAX_NUM_LINES = 1000
    FILE_NAME = "input_file.txt"
    SPLIT_PARAM = "-d"
    PREFIX = "__"
    
    if os.system(f"split -l {MAX_NUM_LINES} {SPLIT_PARAM} {FILE_NAME} {PREFIX}") == 0:
        print("Done:")
        print(os.system(f"ls {PREFIX}??"))
    else:
        print("Failed!")
    

    Read more about split here: https://linoxide.com/linux-how-to/split-large-text-file-smaller-files-linux/

提交回复
热议问题