【问题标题】:Renaming file with os.rename causing NameError使用 os.rename 重命名文件导致 NameError
【发布时间】:2016-04-26 07:14:17
【问题描述】:

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

【问题讨论】:

  • 提醒一下:在正则表达式中 r'.+\.jpg$' 会更好
  • 我试图复制您的确切代码并运行它。它完美地工作。您确定您捕获了代码中最相关的部分吗?看起来错误出在其他地方...您还检查了缩进(制表符和空格)吗?

标签: python python-2.7 rename


【解决方案1】:

堆栈跟踪表明您的 sn-p 不是全部。 我无法重现:

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

【讨论】:

    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    相关资源
    最近更新 更多