簡體   English   中英

從文件名中刪除非字母數字字符並在Python中重命名

[英]Removing non-alphanumeric characters from filenames and rename in Python

我試圖擺脫源文件夾中的非字母數字字符,並且不使用此代碼就將具有非字母數字字符的所有文件重命名為版本。 但是,每次我運行模塊時,都會出現此錯誤,

Traceback (most recent call last):
  File "C:\tempstore\Filescan1", line 18, in <module>
    os.rename(filename,newfilename)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process

請幫助?

os.chdir("C:\\tempstore\\source")
file_list = glob.glob("*.mpg*")
for filename in file_list:
    if re.search('[^A-Za-z0-9._ ]+',filename,re.U) is not None:
        print filename + " <--Dodgy File"
        print re.sub('[^0-9a-zA-Z+_. ]+','-',filename)+ " <--Fixed File"
        newfilename =  re.sub('[^0-9a-zA-Z+_. ]+','-',filename)
        os.rename(filename,newfilename)
    elif re.search('[^A-Za-z0-9._ ]+',filename,re.U) is None:
        print filename +" <-- Normal File"
        unchanged_list = re.sub('[^A-Za-z0-9._ ]+','_',filename)
        print unchanged_list

關閉防病毒軟件,或至少將“按訪問”掃描設置為“關閉”。 我還建議使用re.sub生成newfilename然后將其用於打印和重命名,即:

    print re.sub('[^0-9a-zA-Z+_. ]+','-',filename)+ " <--Fixed File"
    newfilename =  re.sub('[^0-9a-zA-Z+_. ]+','-',filename)

應該讀:

    newfilename =  re.sub('[^0-9a-zA-Z+_. ]+','-',filename)
    print 'Renaming to:', newfilename

並擺脫了示例的最后兩行。

解決了! 出現錯誤的原因是Windows不允許您編輯打開目錄中的文件,而我的程序正在打開目錄來編輯文件。 確實是Catch-22,您不能在打開的目錄中編輯文件,但是必須打開目錄才能編輯文件。 我已經使用shutil.copy移動了文件,然后重命名了文件,對於我的菜鳥行為,這很不錯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM