Split diary file into multiple files using Python

前端 未结 3 796
余生分开走
余生分开走 2021-01-06 17:19

I keep a diary file of tech notes. Each entry is timestamped like so:

# Monday 02012-05-07 at 01:45:20 PM

This is a sample note

Lorem ipsum dolor sit amet,         


        
3条回答
  •  不知归路
    2021-01-06 17:43

    It really doesn't require as much regex as you would think.

    First just load the file so you have it based on new lines:

    fl = 'file.txt'
    with open(fl,'r') as f:
        lines = f.readlines()
    

    now just loop through it! Compare each line with the regex you provided, and if it matches, that means it's a new date!

    Then you will grab the next non-empty line after that and set it as the name of the file.

    Then keep going through and writing lines to that specific file name until you hit another match to your regex, where you know it is now meant to be a new file. Here is the logic loop:

    for line in lines:
        m = re.match(your regex)
        if m:
            new_file = True
        else:
            new_file = False
        #now you will know when it's a new entry so you can easily do the rest
    

    Let me know if you need any more of the logic broken down. Hopefully this was helpful

提交回复
热议问题