本文实例为大家分享了python批量创建指定名称的文件夹具体代码,供大家参考,具体内容如下
继删除多余文件之后,做了一些数据处理,需要重新保存数据,但文件夹的名称又不能改
所以只能创建新的文件夹,换个路径用之前的文件夹名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
import os
import glob
#txt文件生成一次就好,或者用os.walk遍历需要的文件夹名称路径
def mk_text(txt_path):
folders = glob.glob(txt_path + '/*_1' )
writeText = open ( 'F:/my_data/brats18_training/test.txt' , 'w' )
for files in folders:
if len (files) < = 0 :
continue
writeText.write(os.sep + files + ', ' + '\n' )
writeText.close()
def mkdir(mk_path):
test = []
name = []
# =============================================================================
# 或者用下面的程序把三个循环替换
# for line in open('F:/my_data/brats18_training/test.txt', 'r'):
# test.append(line)
#
# for filename in test:
# filename = filename.strip()
# filename = filename.rstrip(',')
# if os.path.basename(filename)[0:7] == 'Brats18':
# name = os.path.join(mk_path + '/' +os.path.basename(filename))
# isExists = os.path.exists(name)
# if not isExists:
# os.mkdir(name)
# print(name +'Successed')
# else:
# print(name + 'This is this content')
# =============================================================================
for line in open ( 'F:/my_data/brats18_training/test.txt' , 'r' ):
test.append(line)
for filename in test:
filename = filename.strip()
filename = filename.rstrip( "," )
if os.path.basename(filename)[ 0 : 7 ] = = 'Brats18' :
name.append(os.path.join(mk_path + '/' + os.path.basename(filename)))
for generate_path in name:
#print(generate_path)
isExists = os.path.exists(generate_path)
if not isExists:
os.mkdir(generate_path)
print (generate_path + '创建成功' )
#千万不要用return
else :
print (generate_path + ' There is this content' )
path = 'F:/my_data/HGG'
mk_path = "H:/data/HGG"
mkdir(mk_path)
mk_txt(path)
|
小编再为大家分享一段:在指定目录批量创建文件夹的python实现代码:
目标文件夹为:L:\ZJ_Landsat\LC81220442013221LGN00\WaterQuality_PCA\results
目录L:\ZJ_Landsat下有大量影像文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import os
rootDir = "L:\ZJ_Landsat"
name1 = "WaterQuality_PCA"
name2 = "results"
folder_name = "PCA_4_bands"
def listDir(rootDir):
dir1 = []
for dirpath, dirnames, filenames in os.walk(rootDir):
for dir in dirnames:
dir1.append(os.path.join(rootDir, dir [ 0 : 21 ])) #LC81220442013221LGN00的长度为21
return dir1
print ( "Done!" )
dirList = listDir(rootDir)[ 0 : 104 ] #104为104个影像文件夹数量
dir1 = []
dir2 = []
for dir in dirList:
dir1 = os.path.join(''.join( dir ),name1)
dir2 = os.path.join(dir1,name2)
dir3 = os.path.join(dir2,folder_name)
if not os.path.exists(dir3):
os.mkdir(os.path.join(dir3))
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_42338058/article/details/84561818