Python 基于Python实现批量创建目录
基于Python实现批量创建目录
by:授客QQ:1033553122
测试环境:
Python版本:Python 2.7
代码实践
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
import os
class PublicTools:
def __init__(self):
pass
# 批量创建目录
def mkdirs_once_many(self, path):
path = os.path.normpath(path) # 去掉路径最右侧的 \\ 、/
path = path.replace('\\', '/') # 将所有的\\转为/,避免出现转义字符串
head, tail = os.path.split(path)
new_dir_path = '' # 反转后的目录路径
root = '' #根目录
if not os.path.isdir(path) and os.path.isfile(path): # 如果path指向的是文件,则继续分解文件所在目录
head, tail = os.path.split(head)
if tail == '':
return
while tail:
new_dir_path = new_dir_path + tail + '/'
head, tail = os.path.split(head)
root = head
else:
new_dir_path = root + new_dir_path
# print(new_dir_path)
# 批量创建目录
new_dir_path = os.path.normpath(new_dir_path)
head, tail = os.path.split(new_dir_path)
temp = ''
while tail:
temp = temp + '/' + tail
dir_path = root + temp
if not os.path.isdir(dir_path):
os.mkdir(dir_path)
head, tail = os.path.split(head)
# if __name__ == '__main__':
# # file_name = 'D:\\tset\\tkise\\FAQ.txt'
# # mkdirs_once_many(file_name)
# # file_name = 'D:\\tset\\tkise\\'
# # mkdirs_once_many(file_name)
# # file_name = 'd:\\'
# # mkdirs_once_many(file_name)
# file_name = r'D:\tset\tkise\FAQ.txt'
# mkdirs_once_many(file_name)
# #file_name = '/tset/tkise/' # Linux下应该可以/未验证
# #mkdirs_once_many(file_name)
作者:授客
微信/QQ:1033553122
全国软件测试QQ交流群:7156436
Git地址:https://gitee.com/ishouke
友情提示:限于时间仓促,文中可能存在错误,欢迎指正、评论!
作者五行缺钱,如果觉得文章对您有帮助,请扫描下边的二维码打赏作者,金额随意,您的支持将是我继续创作的源动力,打赏后如有任何疑问,请联系我!!!
微信打赏
支付宝打赏 全国软件测试交流QQ群