Python:重命名文件

2024-09-30 06:13:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个spimple脚本来重命名目录中的所有文件(例如475435_名称.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'

我不想它移动文件我只想改变名字。在

^{pr2}$

Tags: 文件目录脚本名称most数量错误重命名
2条回答

你需要仔细查看输入的路径,看看文件是否以“.psd”结尾, 尝试此代码段将有助于:

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文件放在同一个路径输入“/”就行了。在

根据@RvrK的评论,脚本试图将重命名的目标指向工作目录,所以我猜最后一行改为:

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

应该这么做吗?在

编辑:

添加一些“安全”功能:

^{pr2}$

相关问题 更多 >

    热门问题