开发者

Renaming OS files

I am trying to rename files based on their extensions. Below is my code, Somehow my os.rename isn't working. There aren't any errors though. I got no idea what is wrong. Hope you guys could help. Thanks.

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) 


I get an error:

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

Anyhow, it looks like you're over complicating things. This works just fine:

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜