简体   繁体   English

Python os.rename,删除和错误捕获

[英]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.如果发生错误,表明该目录中存在重复的命名文件,则异常块使用 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.在 try-except 块之前打印 output 会产生理想的结果,但运行该块不会产生 output ,就像在块之后打印一样。

Why is the try-except block not functioning as intended?为什么 try-except 块没有按预期运行?

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: .注意try:的额外缩进。 Without it, it's not part of the same iteration in for f .没有它,它就不是for f中同一迭代的一部分。 Was it this simple?就这么简单吗? Hopefully =)希望 =)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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