2010-08-13 151 views
0

我想重新命名基於擴展名的文件。下面是我的代碼,不知何故我的os.rename不工作。雖然沒有任何錯誤。我不知道什麼是錯的。希望你們能幫忙。謝謝。重命名操作系統文件

import os 
import glob 
directory = raw_input("directory? ") 
ext = raw_input("file extension? ") 
r = raw_input("replace name") 
pattern = os.path.join(directory, "*" + ext) 
matching_files = glob.glob(pattern) 
file_number = len(matching_files) 



for filename in os.listdir(directory): 
    if ext in filename: 
     path = os.path.join(directory, filename) 
     seperated_names = os.path.splitext(filename)[0] 
     replace_name = filename.replace(seperated_names, r) 
     split_new_names = os.path.splitext(replace_name)[0] 

for pad_number in range(0, file_number): 
    padded_numbers = "%04d" % pad_number 
    padded_names = "%s_%s" % (split_new_names, padded_numbers) 
    newpath = os.path.join(directory, padded_names) 
    newpathext = "%s%s" % (newpath, ext) 


new_name = os.rename(path, newpathext) 
+0

我認爲你的縮進是搞砸了;你可以修復它 – 2010-08-13 15:20:24

+0

@尼克T:請張貼您的答案作爲一個正確的答案,所以我們可以投票。 – 2010-08-13 15:41:06

回答

1

我得到一個錯誤:

directory? c:\breakup 
file extension? .txt 
replace name? test 
Traceback (most recent call last): 
    File "foo.py", line 25, in <module> 
    new_name = os.rename(path, newpathext) 
WindowsError: [Error 2] The system cannot find the file specified 
shell returned 1 

總之,它看起來就像你在複雜的事情。這工作得很好:

import os 
directory = raw_input("directory? ") 
ext = raw_input("file extension? ") 
r = raw_input("replace name? ") 

for i, filename in enumerate(os.listdir(directory)): 
    if filename.endswith(ext): 
     oldname = os.path.join(directory, filename) 
     newname = os.path.join(directory, "%s_%04d%s" % (r, i, ext)) 
     os.rename(oldname, newname)