os模組很多操作檔案目錄等等,直接粘舉例和注釋:
1import
os2 os.makedirs('
a/b/c/d
') #
可生成多層遞迴目錄(此步會當前檔案目錄建立a裡面b,依次類推)
3 os.removedirs('
a/b/c/d
') #
若目錄為空,則刪除,並遞迴到上一級目錄,如若也為空,則刪除,依此類推
4 os.mkdir('
資料夾名字
') #
生成單級目錄;相當於shell中mkdir 資料夾名字
5 os.rmdir('
資料夾名字
') #
刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir 資料夾名字
6print(os.listdir('
..\練習
')) #
列出指定目錄下的所有檔案和子目錄,引數可以是相對絕對路徑或統計資料夾名
7 os.remove("
檔名") #
刪除乙個檔案
8 os.rename("
舊名字","
新名字") #
重新命名檔案/目錄
9print(os.stat(r"
c:\users\xufudong\desktop\練習\1.txt
")) #
獲取檔案/目錄資訊(目錄資訊不准)
1 os.system("dir") #
執行shell命令,直接顯示(可能亂碼)
2print(os.popen("
dir").read()) #
執行shell命令,獲取執行結果(用read讀取)
3 os.chdir("
..\練習
") #
改變當前指令碼工作目錄;相當於shell下cd
4print(os.getcwd()) #
獲取當前工作目錄,即當前python指令碼工作的目錄路徑
下面是os下的路徑相關方法:
1 os.path.abspath(path) #返回path規範化的絕對路徑
2 os.path.split(path) #
將path分割成目錄和檔名二元組返回,例如:('c:\users\xufudong', 'desktop')
3 os.path.dirname(path) #
返回path的目錄。其實就是os.path.split(path)的第乙個元素
4 os.path.basename(path) #
返回path最後的檔名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素
5 os.path.exists(path) #
如果path存在,返回true;如果path不存在,返回false
6 os.path.isabs(path) #
如果path是絕對路徑,返回true
7 os.path.isfile(path) #
如果path是乙個存在的檔案,返回true。否則返回false
8 os.path.isdir(path) #
如果path是乙個存在的目錄,則返回true。否則返回false
9 os.path.join(path) #
將多個路徑組合後返回,第乙個絕對路徑之前的引數將被忽略
10 os.path.getatime(path) #
返回path所指向的檔案或者目錄的最後訪問時間
11 os.path.getmtime(path) #
返回path所指向的檔案或者目錄的最後修改時間
12 os.path.getsize(path) #
返回path的大小
Python中os模組的常用方法
os.getcwd 獲取當前py檔案所在的資料夾路徑 os.mkdir path 建立乙個單層級資料夾 os.makedirs path 建立乙個多層級的資料夾 os.rmdir path 刪除乙個單層級的空資料夾,若資料夾不為空則報錯 os.removedirs path 刪除乙個空資料夾 非空資...
python常用模組之os模組
os模組可以處理檔案和目錄這些日常手動需要做的操作,比如常用的刪除檔案等。此外,os不受平台限制,非常方便。常用功能 1 os.name 顯示當前使用的平台 import os print os.name nt windows2 os.getcwd 顯示當前python指令碼工作路徑 print o...
Python中的os模組
os.listdir dirname 列出dirname下的目錄和檔案 os.getcwd 獲得當前工作目錄 os.curdir 返回當前目錄 os.chdir dirname 改變工作目錄到dirname os.path.isdir name 判斷name是不是乙個目錄,name不是目錄就返回fa...