Python:重命名文件错误

时间:2015-01-09 14:21:44

标签: python batch-rename

我有一个spimple脚本来重命名目录中的所有文件(例如475435_name.psd),方法是增加它的数字,比如10。

但是我收到了错误

Traceback (most recent call last):
  File "C:/Users/mstopienski/Desktop/Desktop/test.py", line 12, in <module>
    os.rename(filename, newname)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '810858_Hero_ProjectHP_1600x487.psd' -> '810868_Hero_ProjectHP_1600x487.psd'

我不希望它移动文件我只想更改名称。

import glob, os
path = input()
for filename in glob.glob(path):
    number = filename[0:6]
    name = filename[6:]
    x = int(number)+10
    newname = (str(x) + name)
    os.rename(filename, newname)

2 个答案:

答案 0 :(得分:0)

根据@RvrK的评论,该脚本正在尝试定位重命名的工作目录,因此我猜测将最后一行转为:

os.rename(os.path.join(path, filename), os.path.join(path, newname)) 

应该这样做吗?

编辑:

添加一些'安全'功能:

import glob, os
path = input()
for filename in glob.glob(path):
    basename = os.path.basename(filename)
    number = basename [0:6]
    name = basename [6:]
    x = int(number)+10
    newname = (str(x) + name)
    os.rename(os.path.join(path, filename), os.path.join(path, newname)) 

答案 1 :(得分:0)

您需要查看输入的路径并查看文件是否以&#39; .psd&#39;结尾, 试试这段代码会有所帮助:

import os
path = raw_input()
for filename in os.walk(path):
  for ele in filename:
    if type(ele) == type([]) and len(ele)!=0:
      for every_file in ele:
        if every_file.endswith('psd'):

           number = every_file[0:6]
           name = every_file[6:]
           x = int(number)+10
           newname = (str(x) + name)
           os.rename(os.path.join(path, every_file), os.path.join(path, newname))

我把脚本和你的psd文件放在同一路径输入&#34; ./"它有效。