Python - rename files in subfolders based on subfolder and file name

喜你入骨 提交于 2019-12-23 06:11:38

问题


I have a folder, C:\temp, with subfolders and files like below:

\11182014\

VA1122F.A14  
VA9999N.A14  
CT3452F.B13  
CT1467A.B14

\12012014\

MT4312F.B14  
MT4111N.B14  
CT4111F.A12

The file extensions are always an ".A" or ".B" followed by 2 digits. The file names always end with an "F", "A", or "N".

I would like to loop through all subfolders in C:\temp and:

  • prefix each file with "My_X_" where X is either an F, N, or A (i.e., the last letter in the file name)

  • suffix each file with "_" + the name of the subfolder

The result would be:

\11182014\

My_F_VA41245F_1182014.A14  
My_N_VA43599N_1182014.A14  
My_F_CT41111F_1182014.B13  
My_A_CT41112A_1182014.B14  

\12012014\

My_F_MT4312F_12012014.B14  
My_N_MT4111N_12012014.B14  
My_F_CT4111F_12012014.A12 

Any suggestions?


回答1:



    #!/usr/bin/env python
# ---*--- coding:utf-8 ---*---

import os

path = "/home/username/test"

for root,dirname,filename in os.walk(path):
    for i in filename:
        i = i.split(".")
        first = i[1][0]
        last = i[0][-1]
        print "My_"+last+i[0]+root+"."+i[1]




回答2:


This will do

fld = '/Your/path/to/main/folder/'

for root, subdirs, files in os.walk(fld):
    for name in files:
        curr_fld = os.path.basename(root)
        oldname = os.path.join(fld, curr_fld, name)
        splt_name =  name.split('.')
        myname = '_'.join(['My', splt_name[0][-1], splt_name[0], curr_fld + '.' + splt_name[1]])
        newname = os.path.join(fld, curr_fld, myname)
        os.rename(oldname, newname)


来源:https://stackoverflow.com/questions/31435984/python-rename-files-in-subfolders-based-on-subfolder-and-file-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!