2016-01-20 14 views
3

我想2個光柵文件重命名:old_name.jpgold_name.tiffnew_name.jpgnew_name.tiff重命名文件引起NameError

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

只是一個平視:「 + \ JPG $」在正則表達式A R會更好 –

+2

我試圖複製你的確切的代碼並運行它。它完美的工作。你確定你捕獲了代碼中最相關的部分嗎?它看起來像錯誤是其他地方...你還檢查了你的縮進(製表符和空格)? – toti08

回答

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