欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

批量创建固定格式的文件夹&&移动文件&&更改文件名

程序员文章站 2022-06-08 10:20:12
...
import os
os.path.splitext('vsdsd.txt')
# ('vsdsd', '.txt')
os.path.splitext('vessel_0.txt')[0]
# 'vessel_0'
os.path.splitext('vessel_0.txt')[0]
# 'vessel_0'
os.path.splitext('vessel_0.txt')[0].replace('_','')
# 'vessel0'

 

 

import os,shutil

import re
root = "/home/xx/桌面/result"

# 创建文件夹并将相应的文件移动到对应的位置,同时将文件名统一更改为result.txt
def mkdir2():
    for i in range(8):
        m = str(i).zfill(2)
        src_root = "/home/xx/PycharmProjects/xx/xx/result/result0{}/xx/".format(i)
        file_list = os.listdir(src_root)
        for j in range(4):
            # n = str(i).zfill(2)

            path = os.path.join(root, f'dataset{m}', f'vessel{j}')
            # print(path) # /home/xx/桌面/result2/result07/vessel3
            # print(os.path.split(path)[1])
            if not os.path.exists(path):
                os.makedirs(path)
                if len(file_list) > 0:
                    for file in file_list:
                        if  re.split(r"/",src_root)[-3][-1] == re.split(r"/", path)[-2][-1]  and os.path.splitext(file)[0].replace('_','') == os.path.split(path)[1]:
                            shutil.copy(src_root+"/"+file, path+"/"+file)
                            os.rename(path+"/"+file, path + "/result.txt")
                            break

if __name__ == '__main__':
    mkdir2()