gpt4 book ai didi

python - 意外的名称错误

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:19 24 4
gpt4 key购买 nike

我正在编写一个脚本来批量重命名文件夹中的所有文件。我试图将其模块化,因此核心算法(生成新文件名的算法)很容易交换。

这是我到目前为止所得到的:

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 "<pyshell#39>", line 1, in <module>
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'

最佳答案

不要为此使用 exec 或 eval,只写

new = algorithm(i, file_index, data, data2)

确保您的所有算法都可以使用这 4 个参数(忽略它们不需要的参数)。

如果你不喜欢这个,下面的代码比使用 eval 更 pythonic 和高效:

args = [i] 
if counter:
args.append(file_index)
for arg in (data, data2):
if arg is not None:
args.append(arg)

new = algorithm(*args)

同样更换丑陋的:

for i in files_list:
file_index = files_list.index(i)

for index, filename in enumerate(file_list):
...

最后,使用 os.path.join 连接路径部分而不是字符串连接。当您使用不带尾随“/”的目录名称调用函数时,这将节省您的调试时间

关于python - 意外的名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6732562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com