问题
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