简体   繁体   中英

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 :

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

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. I tried using shutil.move() , but got the same error. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM