使用os.rename重命名文件导致NameError

时间:2016-01-20 12:27:51

标签: python python-2.7 rename

我正在尝试重命名2个光栅文件:old_name.jpgold_name.tiffnew_name.jpgnew_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(),但得到了同样的错误。有什么问题?

1 个答案:

答案 0 :(得分:2)

堆栈跟踪表明您的代码段不是整个故事。 我无法重现:

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()

但我冒昧地改写了一下。

> 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