Win10的Python3环境下,在指定文件夹下建立多个子文件夹,每个子文件夹中写入示例文件。
os.makedirs() 用来建立多级目录
os.chdir() 用来改变当前路径到目标路径下面,注意目标路径要用绝对路径
import os
for i in range(1, 11):
mulu_number = 'MuLu{}'.format(i)
print(mulu_number)
path_start = r'F:\MuLuJianLi\Test'
path_name = os.path.join(path_start, mulu_number) # 将参考目录与子文件夹组成的路径进行拼接
print('path_name: {}'.format(path_name))
print('当前路径为:{}'.format(os.getcwd())) # 当前目录
if not os.path.exists(path_name):
os.makedirs(path_name) # 如果指定的路径不存在,新建
os.chdir(path_name) # 将当前路径改变到目标路径下
print('改变后路径为:{}'.format(os.getcwd())) # 改变后的路径
file_name = 'Test_{}.txt'.format(i)
with open(file_name, 'w') as f:
f.write('你好,这是第{}个测试'.format(i))
运行过程显示: