【问题标题】:Renaming Multiple Files at Once in a Directory一次重命名目录中的多个文件
【发布时间】: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 比较陌生,似乎无法弄清楚在哪里编辑我的代码。任何提示或建议将不胜感激!

【问题讨论】:

    标签: python directory rename


    【解决方案1】:

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

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

    您需要告诉 Python 要重命名的文件的实际路径 - 否则,它只会在包含该文件的目录中查找。

    顺便说一句,最好不要使用dir 作为变量名,因为那是内置函数的名称。

    【讨论】:

    • 成功了!谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 2012-12-27
    • 2019-07-21
    • 2018-08-29
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多