【随时记录好用的代码 以防后续使用忘记 整体思路源于自己搜索+总结】
——————————————————————————————————————
如果遇到一个人一个文件夹内部还带有一个子文件的情况,还有好几个人,就很让人头疼。想着把子文件名换成当前所在文件夹的人名部分(不要编号),也许会方便检索一点。(开头的一些废话,不用看)
现在的情况:
目标结果:
所需代码如下:
import os
# Change the file name to be the same as the current folder name
def change_name(path):
flag = 0
for root, dirs, files, in os.walk(path):
# Skip the first loop and print root, dirs, files to see why
if flag == 0:
flag = 1
continue
# Get the Chinese part of folder name
folderName = root.split('/')[-1]
folderName_C = folderName.split('_')[1]
# Only one file in each folder, so get the first file (Modify as needed)
fileName = files[0]
# Filename without suffix
fileNameNoSuffix = fileName.split('.')[0]
# Suffix default as empty
suffix = ''
# Sequentially store file suffixes different from the folder name
if(fileName != fileNameNoSuffix):
suffix = '.' + fileName.split('.')[1]
# Rename
originName = path + folderName + '/' + fileName
newName = path + folderName + '/' + folderName_C + suffix
os.rename(originName, newName)
change_name(r'./AAAA Hospital/EyeKnow0/')