2017-08-11 90 views
0

我试图从一个目录中取出一个文件名,例如'OP 40 856101.txt',删除.txt,将每个单词设置为特定变量,然后重新排列文件名基于“856101 OP 040”等所需的顺序。下面是我的代码:一次在目录中重命名多个文件

import os 


dir = 'C:/Users/brian/Documents/Moeller' 
orig = os.listdir(dir)     #original names of the files in the folder 

for orig_name in orig:    #This loop splits each file name into a list of stings containing each word 
    f = os.path.splitext(orig_name)[0] 
    sep = f.split()    #Separation is done by a space 
    for t in sep:   #Loops across each list of strings into an if statement that saves each part to a specific variable 
     #print(t) 
     if t.isalpha() and len(t) == 3: 
      wc = t 
     elif len(t) > 3 and len(t) < 6: 
      wc = t 
     elif t == 'OP': 
      op = t 
     elif len(t) >= 4: 
      pnum = t 
     else: 
      opnum = t 
      if len(opnum) == 2: 
       opnum = '0' + opnum 
    new_nam = '%s %s %s %s' % (pnum,op,opnum, wc)   #This is the variable that contain the text for the new name 

    print("The orig filename is %r, the new filename is %r" % (orig_name, new_nam)) 
    os.rename(orig_name, new_nam) 

但是我正在用我最后的for循环的错误,我尝试重命名目录中的每个文件。

FileNotFoundError: [WinError 2] The system cannot find the file specified: '150 856101 OP CLEAN.txt' -> '856101 OP 150 CLEAN' 

的代码完全运行,直到os.rename()命令,如果我打印出变量new_nam,它打印出的所有目录中的文件的正确的命名顺序。似乎它找不到原始文件,尽管将文件名替换为new_nam中的字符串。我认为这是一个目录问题,但是我对Python更新,似乎无法找到编辑我的代码的位置。任何提示或建议将不胜感激!

回答

1

试试这个(只是改变最后一行):

 os.rename(os.path.join(dir,orig_name), os.path.join(dir,new_nam)) 

你需要告诉Python的文件的实际路径重命名 - 否则,它看起来只有在包含该文件的目录。

顺便提一句,最好不要使用dir作为变量名称,因为这是一个内置的名称。

+0

工作!谢谢!! – Bkal05