簡體   English   中英

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

[英]Renaming file with os.rename causing NameError

我正在嘗試將兩個光柵文件: old_name.jpgold_name.tiff重命名為new_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() ,但得到了同樣的錯誤。 問題是什么?

堆棧跟蹤表明您的代碼段不是整個故事。 我無法重現:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM