[英]Renaming file with os.rename causing NameError
I'm trying to rename 2 raster files: old_name.jpg
and old_name.tiff
to new_name.jpg
and new_name.tiff
: 我正在尝试将两个光栅文件: 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"))
It works on jpg like charm, but then throws 它像魅力一样在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
Note that it uses new_name
to rename jpg, but then variable vanishes in the very next block. 请注意,它使用new_name
重命名jpg,但随后变量在下一个块中消失。 I tried using shutil.move()
, but got the same error. 我尝试使用shutil.move()
,但得到了同样的错误。 What is the problem? 问题是什么?
The stack trace suggests that your snippet isn't the whole story. 堆栈跟踪表明您的代码段不是整个故事。 I can't reproduce: 我无法重现:
from __future__ import division, print_function, unicode_literals
import os
TargetDir = '/tmp/test'
new_name = 'new_name'
def main():
for root_dir, _, filenames in os.walk(TargetDir):
for filename in filenames:
if '.' not in filename:
continue
endswith = filename.rsplit('.', 1)[-1].lower()
if endswith not in set(['jpg', 'tiff']):
continue
new_filename = '{}.{}'.format(new_name, endswith)
from_fn = os.path.join(root_dir, filename)
to_fn = os.path.join(root_dir, new_filename)
print ('Moving', from_fn, 'to', to_fn)
os.rename(from_fn, to_fn)
if __name__ == '__main__':
main()
but I took the liberty of rewriting a bit. 但我冒昧地改写了一下。
> python hest.py
Moving /tmp/test/narf.jpg to /tmp/test/new_name.jpg
Moving /tmp/test/bla.tiff to /tmp/test/new_name.tiff
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.