Search code examples
pythonfilenames

Reading files based on file name and not data type


I am very new to python. I want to read files based on file name and not data type. Say I have Hello.txt_1, Hello.txt_2, Hello.txt_3 in a folder and these files are created automatically by an external code with Hello.txt_3 being the latest file. Now, I want to read the latest created file Hello.txt_3 and check for its contents. How is to be done in python ? I have figured out for files with common data type but not for common file name.


Solution

  • Use glob to perform wildcard matching. The following example will find all the files named as you state and last_file will contain the name of the latest by creation time (or None if no files were found).

    import glob
    import os
    
    last_file = None
    time=0
    for i in glob.glob("Hello.txt_*"):
        if os.path.getctime(i) > time: 
            last_file = i
    

    PS: This question is at the very beginner level however and should have been easily solved by googling.