【发布时间】:2016-04-26 07:14:17
【问题描述】:
我正在尝试将 2 个光栅文件:old_name.jpg 和 old_name.tiff 重命名为 new_name.jpg 和 new_name.tiff:
new_name = 'new_name' # defining new name here
for root_dir, dirname, filenames in os.walk(TargetDir):
for file in filenames:
if re.match(r'.*.jpg$', file, re.IGNORECASE) is not None: # converting jpg
os.rename(os.path.join(root_dir, file), os.path.join(root_dir, new_name + ".jpg"))
if re.match(r'.*.tiff$', file, re.IGNORECASE) is not None: # converting tiff
os.rename(os.path.join(root_dir, file), os.path.join(root_dir, new_name + ".tiff"))
它像魅力一样适用于jpg,但随后抛出
Traceback (most recent call last):
File "C:/!Scripts/py2/meta_to_BKA.py", line 66, in <module>
os.rename(os.path.join(root_dir, file), os.path.join(root_dir, new_name + ".tiff"))
NameError: name 'new_name' is not defined
请注意,它使用new_name 重命名jpg,但随后变量在下一个块中消失。我尝试使用shutil.move(),但得到了同样的错误。有什么问题?
【问题讨论】:
-
提醒一下:在正则表达式中 r'.+\.jpg$' 会更好
-
我试图复制您的确切代码并运行它。它完美地工作。您确定您捕获了代码中最相关的部分吗?看起来错误出在其他地方...您还检查了缩进(制表符和空格)吗?
标签: python python-2.7 rename