重命名OS文件

时间:2010-08-13 15:15:17

标签: python

我正在尝试根据扩展名重命名文件。下面是我的代码,不知怎的,我的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) 

1 个答案:

答案 0 :(得分: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)