我正在编写一个脚本来批量重命名文件夹中的所有文件.我试图使其模块化,因此核心算法(生成新文件名的算法)很容易交换.
这是我到目前为止所得到的:
from os import listdir, rename
def renamer(path, algorithm, counter=False, data=None, data2=None, safe=True):
call_string = 'new=algorithm(i'
if counter:
call_string += ', file_index'
if data != None:
call_string += ', data'
if data2 != None:
call_string += ', data2'
call_string += ')'
if safe:
print('Press Enter to accept changes. '+
'Type anything to jump to the next file.\n')
files_list = listdir(path)
for i in files_list:
file_index = files_list.index(i)
old = i
exec(call_string)
if safe:
check = input('\nOld:\n'+old+'\nNew:\n'+new+'\n\nCheck?\n\n')
if check is not '':
continue
rename(path+old, path+new)
return
现在由于某种原因(对我来说似乎无法解释),调用该函数会引发NameError:
>>> def f(s):
return 'S08'+s
>>> path='C:\\Users\\****\\test\\'
>>> renamer(path, f)
Press Enter to accept changes. Type anything to jump to the next file.
Traceback (most recent call last):
File "", line 1, in
renamer(path, f)
File "C:\Python32\renamer.py", line 25, in renamer
check = input('\nOld:\n'+old+'\nNew:\n'+new+'\n\nCheck?\n\n')
NameError: global name 'new' is not defined
难以理解,因为在第25行它应该已经执行了call_string,从而定义了名称new.
我一直试图弄清楚我的错误超过一个小时了,我已经完成整个代码进入线路两次进入shell,它运行良好,我似乎无法弄清楚问题.
有人可以帮我弄清楚我哪里出错了吗?
编辑:
我已经猜到你可能无法使用exec分配名称,所以我测试了它如下,它工作:
>>> exec('cat="test"')
>>> cat
'test'