天天看點

Python程式設計:os子產品

os屬性

import os

print(os.curdir) # 目前目錄 .
print(os.pardir) # 父目錄 ..
print(os.name)  # 平台名稱 win nt linux posix
print(os.sep)  # separator路徑分隔符win \\ linux /
print(os.linesep) # 行終止符 win \r\n  linux \n
print(os.pathsep)  # 分隔檔案路徑 ;
print(os.extsep)  # extension擴充名 .      

os方法

import os

print(os.getcwd())  # 傳回目前工作目錄
print(os.chdir( r"dir" ))  # 改變工作目錄,相當于shell下cd
os.makedirs("dir1/dir2")  # 生成多層遞歸目錄,存在則無法建立
os.removedirs("dir1/dir2")  # 遞歸删除空目錄
os.mkdir("dirname")  # 生成單級目錄,存在則無法建立
os.rmdir("dirname")  # 删除單級空目錄,不為空則無法删除
print(os.listdir())  # list傳回指定目錄下所有檔案和子目錄,包括隐藏檔案
os.remove("file.txt") # 删除一個檔案
os.rename("oldname", "newname")  # 重命名檔案/目錄

os.system("ipconfig /all")  # 運作shell指令,直接顯示
print(os.environ) # 傳回系統環境變量      

path子產品

import os

print(os.path.abspath("file.txt"))  #傳回絕對路徑
print(os.path.split("dirname/file.txt"))  #tuple分隔目錄和檔案名
print(os.path.splitext("file.txt"))  #tuple分隔檔案名和擴充名  (file, .txt)
print(os.path.dirname("dirname/file.txt"))  #傳回目錄
print(os.path.basename("dirname/file.txt")) # 傳回檔案名
print(os.path.join("dir","file.txt")) # 傳回一個組合路徑

print(os.path.exists("file.txt")) # bool判斷檔案是否存在
print(os.path.isabs("file.txt")) # bool判斷是否為絕對路徑
print(os.path.isfile("file.txt")) # bool判斷是否為一個檔案
print(os.path.isdir("dir")) # bool判斷是否為一個目錄

print(os.stat("file.txt"))  # tuple擷取檔案/目錄資訊
print(os.path.getatime("file.txt")) # 時間戳,傳回最後存取時間
print(os.path.getmtime("file.txt")) # 時間戳,傳回最後修改時間

# 時間戳轉為格式化時間字元串
# time.strftime("%Y-%m-%d %H:%M:%S",time.localtime("timestamp")      

周遊所有檔案和檔案夾

import os

# 遊走目錄樹
for root, dirs, files in os.walk("."):
    for file in files:
        print(os.path.join(root, file))
    for dir in dirs:
        print(os.path.join(root, dir))      

help(os)

  • all functions from posix, nt or ce, e.g. unlink, stat, etc.
  • os.path is either posixpath or ntpath
  • os.name is either ‘posix’, ‘nt’ or ‘ce’.
  • os.curdir is a string representing the current directory (‘.’ or ‘:’)
  • os.pardir is a string representing the parent directory (‘..’ or ‘::’)
  • os.sep is the (or a most common) pathname separator (‘/’ or ‘:’ or ‘\’)
  • os.extsep is the extension separator (always ‘.’)
  • os.altsep is the alternate pathname separator (None or ‘/’)
  • os.pathsep is the component separator used in $PATH etc
  • os.linesep is the line separator in text files (‘\r’ or ‘\n’ or ‘\r\n’)
  • os.defpath is the default search path for executables
  • os.devnull is the file path of the null device (‘/dev/null’, etc.)