简体   繁体   中英

Check file extensions with Regex

I am writing a script to change the name of the video file based on the subtitle files using regular expression.

for files in curDir:
    if re.search(r'.*[.srt]$',files): #1
        print files;
    if re.search(r'.*[^.srt]$',files): #2
        print files;

During execution what I found was that the #1 if condition is executed continuously so that all the .srt files are printed then only #2 if condition is executed and all video files are printed.

Shouldn't those if conditions be executed alternately for each files like first #1 and then #2 ?

I think my problem is the way in which the re.search returns results. So, I need help to access the if conditions one after another for each files.

You do not need Regex to check whether or not the filenames end in .srt . str.endswith will do this easily:

for files in curDir:
    if files.endswith('.srt'):  # Filename ends in .srt
        ...
    else:                       # Filename does not end in .srt
        ...

Regex should only be used when you have complex patterns to match (and then, by all means, use it!). Otherwise, it should be avoided because it is slower than Python's built-in tools and also somewhat difficult for people who are not experienced with it.

sorry I can not comment to existing answers yet. just want to point out that it'd be better to use what's in the chosen answer with tiny modification:

for file in curDir:
    if file.lower().endswith('.srt'):  # Filename ends in .srt
        ...
    else:                       # Filename does not end in .srt
        ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM