简体   繁体   中英

Python os.rename, remove and error catching

The script gets filenames from a directory, splits the file name and the extension. Characters ) and. are then removed from the file name and thus the file name is renamed. If an error occurs that indicates that a duplicate named file exists from that directory, it is handled by the exception block using os.remove. Printing the output before the try-except block produces desirable results but running the block produces no output as does printing after the block.

Why is the try-except block not functioning as intended?

import os
import re

os.chdir('E:\D\Music\Music V')

for f in os.listdir(): 
    fileName, fileExt =  os.path.splitext(f) 
    fileName = re.sub('[).]','',fileName)
    newName = '{}{}'.format(fileName, fileExt)

    #print(newName)

try:
    os.rename(f, newName)
except WindowsError:
    os.remove(newName)
    os.rename(f, newName)

    #print(newName)

So this worked for me:

import os
import re

os.chdir('E:\D\Music\Music V')

for f in os.listdir(): 
    fileName, fileExt =  os.path.splitext(f) 
    fileName = re.sub('[).],'',filename)
    newName = '{}{}'.format(fileName, fileExt)

    #print(newName)

    try:
        os.rename(f, newName)
    except WindowsError:
        os.remove(newName)
        os.rename(f, newName)

        #print(newName)

Note that the extra indent for try: . Without it, it's not part of the same iteration in for f . Was it this simple? Hopefully =)

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