python中nameerror怎么处理_python – 意外的NameError

作者分享了一段关于编写脚本批量重命名文件夹内文件的代码,遇到‘NameError: global name 'new' is not defined’的问题。文章探讨了代码执行过程中的变量定义问题,并尝试了exec函数的使用。寻求帮助理解为何在函数内部new未被正确定义。
摘要由CSDN通过智能技术生成

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

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

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'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值