首先要導入os模塊python
import os
#新建一個文件夾函數
os.mkdir('python11')
#刪除一個文件夾
code
os.rmdir('python11')
#新建一個文件orm
open('python11/huli.txt','a+')
#刪除一個文件rem
os.remove('python11/huli.txt')
#路徑的獲取1 獲取當前工做目錄 具體到最後一級目錄get
path=os.getcwd() print("1獲取到的當前路徑是:{0}".format(path))
# #路徑獲取2 獲取當前文件所在的絕對路徑 具體到 模塊名it
path_2=os.path.realpath(__file__)#__file__一個靜態變量,表示當前文件 print("2獲取到的當前路徑是:{0}".format(path_2))
#路徑的獲取3:拼接路徑
#一、用'+'拼接form
path = os.getcwd()+ '\python12' # os.mkdir(path)
#二、os.path.join()函數拼接class
path=os.path.join(os.getcwd(),'python12','huli') os.mkdir(path)
#判斷是文件仍是目錄
#isfile和isdir參數必須爲絕對路徑import
print(os.path.isfile(__file__))#返回值 布爾值 print(os.path.isdir(os.getcwd()))#返回值 布爾值
#怎麼去判斷文件是否存在呢? 返回布爾值
print(os.path.exists('huli.txt')) print(os.path.exists("E:\2018Python課件&代碼\code\python_11\class_1013\class_02.py"))
#羅列出當前路徑的全部文件和目錄
print(os.listdir(os.getcwd()))
下面是一個小練習,打印出一個目錄下全部文件
def show_file(path): for item in os.listdir(path): new_path=os.path.join(path,item) if os.path.isfile(new_path): pass print('當前{0}路徑下的文件爲{1}'.format(path,item)) else: print('當前{0}路徑下的文件夾爲{1}'.format(path, item)) show_file(new_path) show_file(os.getcwd())