1. 程式人生 > >python的檔案和目錄操作

python的檔案和目錄操作

一 獲得當前路徑 1、程式碼1
  1. >>>import os
  2. >>>print('Current directory is ',os.getcwd())
  3. Current directory is D:\Python36
2、程式碼2 如果將上面的指令碼寫入到檔案再執行
  1. Current directory is E:\python\work
二 獲得目錄的內容
>>> os.listdir (os.getcwd())
['DLLs','Doc','include','Lib','libs','LICENSE.txt','NEWS.txt','PyOpenGL-wininst.log','python.exe','python3.dll','python36.dll','pythoncom36.dll','pythonw.exe','pywin32-wininst.log','pywintypes36.dll','RemovePyOpenGL.exe','Removepywin32.exe','Scripts','tcl','Tools','vcruntime140.dll']
三 建立目錄
  1. >>>import os
  2. >>> os.mkdir('temp')
四 刪除目錄
  1. >>> os.rmdir('temp')
五 判斷是否是目錄
  1. >>> os.path.isdir('E:\\python')
  2. True
六 判斷是否是檔案
  1. >>> os.path.isfile('E:\\python\\work\\test.py')
  2. True