Python/Regex - How to extract date from filename using regular expression?

前端 未结 5 1167
滥情空心
滥情空心 2020-11-27 08:05

I need to use python to extract the date from filenames. The date is in the following format:

month-day-year.somefileextension

Examples:

5条回答
  •  情歌与酒
    2020-11-27 08:55

    **This is simple method to find date from text file in python**
    import os
    import re
    file='rain.txt' #name of the file
    if(os.path.isfile(file)): #cheak if file exists or not
        with open(file,'r') as i:
            for j in i: #we will travarse line by line in file 
                try:
                    match=re.search(r'\d{2}-\d{2}-\d{4}',j) #regular expression for date
                    print(match.group()) #print date if match is found
                except AttributeError: 
                    pass
    else:
        print("file does not exist")
    

提交回复
热议问题