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:\test'

#創建目錄
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('\n當前目錄下的文件列表如下:')
#循環當前目錄下的文件列表
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:\test'):
    shutil.move(r'D:\test',r'E:\test')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM