Python中利用os模块创建目录文件

一、os.makedirs()

  os.makedirs() 方法用于递归创建目录。像 mkdir(), 但创建的所有intermediate-level文件夹需要包含子目录。

import os

path_01 = 'Test\path_01\path_02\path_03'

try:
    os.mkdir(path_01)
    print('第一次创建成功!')

except:
    print('第一次创建失败!')
    try:
        os.makedirs(path_01)
        print('第二次创建成功!')
    except:
        print('第二次创建失败!')
#结果:第一次创建失败!
           第二次创建成功!

os.mkdir()      创建路径中的最后一级目录,即:只创建path_03目录,而如果之前的目录不存在并且也需要创建的话,就会报错。

os.makedirs()创建多层目录,即:Test,path_01,path_02,path_03如果都不存在的话,会自动创建,但是如果path_03也就是最后一级目录      

路径创建  eg:

import os

path = 'd/test1/makefile/two'       #path ='d\test1\makefile\two'   转义方法      
os.makedirs(path,mode=0o770)     #mode权限模式   
print('路径被创建')        

循环创建eg:

for i in range(5):
path='cest'+'\'+"ciliylist[%d]"%i
if not os.path.exists(path):
os.makedirs(path)
file=open(path+'/a.txt','w',encoding='utf-8')
file.write('成功创建路径%d'%i)
file.close()

 二、文件目录操作 

#!/usr/bin/python
# encoding=utf-8
# Filename: dir_file.py
import os
import shutil


#操作目录
opDir=r'D:	est'

#创建目录
if not os.path.exists(opDir):
    os.mkdir(opDir)

#更改当前目录到opDir
os.chdir(opDir)

#显示当前目录
print('当前目录是:%s'%os.getcwd())

#创建多级目录
if not os.path.exists(opDir+os.sep+"aa"+os.sep+"bb"):
    os.makedirs(opDir+os.sep+"aa"+os.sep+"bb")
    
#在当前目录下创建文件
if not os.path.exists('test.txt'):
    f=open('test.txt',"w")
    f.write("write something to file")
    f.close()
    
#读取文件内容
print '文件内容如下:'
if os.path.exists('test.txt'):
    f=open('test.txt')
    while True:
        line = f.readline()
        if len(line) == 0: # Zero length indicates EOF
            break
        print(line)
    f.close()

#打印一个空行
print('
当前目录下的文件列表如下:')
#循环当前目录下的文件列表
lfile=os.listdir(os.getcwd())
for sfileName in lfile:
    if os.path.isdir(sfileName):
        print('目录%s' % sfileName)
    elif os.path.isfile(sfileName):
        print('文件%s' % sfileName)
        
#删除目录(只能删除空目录)
if os.path.exists("dd"):
    os.rmdir("dd")
    
#删除文件
if os.path.exists("aa"):
    shutil.rmtree("aa")
    
#修改目录或文件的名称
if os.path.exists("test"):
    os.rename("test", "test2")
    
#移动目录
if os.path.exists(r'D:	est'):
    shutil.move(r'D:	est',r'E:	est')
原文地址:https://www.cnblogs.com/mainstream/p/11275834.html