【发布时间】:2018-01-19 10:36:36
【问题描述】:
我正在尝试从目录中获取文件名,例如“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 比较陌生,似乎无法弄清楚在哪里编辑我的代码。任何提示或建议将不胜感激!
【问题讨论】: