python的標準庫有很多,還有第三方庫,多的都學不過來了,千里之行始於足下,每週學兩到三個模塊,慢慢的就掌握的多了,學習的過程中做一下筆記,或許能給想學習相關模塊的人以一些幫助......
1、遍歷文件夾(os.walk)
文件夾(C:\Users\Desktop\Python)描述:
該文件夾下包含一個文件夾(標準庫)和一個文件(Python核心編程(第二版).pdf)
文件夾(標準庫)下包含一個文件(51CTO下載-python標準庫.pdf)
代碼:
import os
directory = "C:\Users\Desktop\Python"
for parent,dirnames,filenames in os.walk(directory):
print parent
for dirname in dirnames:
print dirname
print os.path.join(parent,dirname)
for filename in filenames:
print filename
print os.path.join(parent,filename)
程序說明:
os.walk將目錄一級一級的遍歷,程序中的parent,dirnames,filenames分別指的是父級目錄,文件夾,文件
第一次遍歷,父級目錄爲C:\Users\Desktop\Python,文件夾爲 標準庫,文件名爲Python核心編程(第二版).pdf
故輸出結果:
C:\Users\Desktop\Python
標準庫
C:\Users\Desktop\Python\標準庫
Python核心編程(第二版).pdf
C:\Users\Desktop\Python\Python核心編程(第二版).pdf
第二次遍歷,父級目錄爲C:\Users\Desktop\Python\標準庫,文件夾爲空,文件名爲51CTO下載-python標準庫.pdf
故輸出結果:
C:\Users\Desktop\Python\標準庫
51CTO下載-python標準庫.pdf
C:\Users\Desktop\Python\標準庫\51CTO下載-python標準庫.pdf
程序結束
2、獲取當前目錄
os.getcwd()
3、創建與刪除目錄(makedirs,mkdir,removedirs,rmdir)
mkdir與makedirs
makedirs當中間目錄沒有的情況下回自動創建以保證所要的目錄能夠創建完成
比如:在目錄D:\資料下創建D:\資料\python\linux,儘管沒有目錄D:\資料\python還是會創建成功
而mkdir就不會創建,報錯
rmdir與removedirs
首先說明:
這兩個函數只能刪除空文件夾(注意是空的,並且是文件夾)
rmdir只能刪除最後一級的空文件夾
remove刪除所有空的文件夾
4、os.path
代碼:
import os
directory = "C:\Users\Desktop\Python"
for parent,dirnames,filenames in os.walk(directory):
file1 = parent
for dirname in dirnames:
file2 = os.path.join(parent,dirname)
for filename in filenames:
file3 = os.path.join(parent,filename)
files = []
files.extend([file1,file2,file3])
for File in files:
print File,"-->",
if os.path.isabs(File):
print "isabs",
if os.path.isdir(File):
print "isdir",
if os.path.isfile(File):
print "isfile",
if os.path.exists(File):
print "exists"
break
結果:
C:\Users\Desktop\Python --> isabs isdir exists
C:\Users\Python\標準庫 --> isabs isdir exists
C:\Users\Desktop\Python\Python核心編程(第二版).pdf --> isabs isfile exists
5、os執行操作系統的命令
代碼:
import os
os.system("ls")
結果: