1. 程式人生 > >os.path等os模塊函數

os.path等os模塊函數

text 支持 href names -i spl lose with mount

os.path.abspath(path) #返回絕對路徑 os.path.basename(path) #返回文件名 os.path.commonprefix(list) #返回list(多個路徑)中,所有path共有的最長的路徑。 os.path.dirname(path) #返回文件路徑 os.path.exists(path) #路徑存在則返回True,路徑損壞返回False os.path.lexists #路徑存在則返回True,路徑損壞也返回True os.path.expanduser(path) #把path中包含的"~"和"~user"轉換成用戶目錄 os.path.expandvars(path) #根據環境變量的值替換path中包含的”$name”和”${name}” os.path.getatime(path) #返回最後一次進入此path的時間。 os.path.getmtime(path) #返回在此path下最後一次修改的時間。 os.path.getctime(path) #返回path的大小 os.path.getsize(path) #返回文件大小,如果文件不存在就返回錯誤 os.path.isabs(path) #判斷是否為絕對路徑 os.path.isfile(path) #判斷路徑是否為文件 os.path.isdir(path) #判斷路徑是否為目錄 os.path.islink(path) #判斷路徑是否為鏈接 os.path.ismount(path) #判斷路徑是否為掛載點() os.path.join(path1[, path2[, ...]]) #把目錄和文件名合成一個路徑 os.path.normcase(path) #轉換path的大小寫和斜杠 os.path.normpath(path) #規範path字符串形式 os.path.realpath(path) #返回path的真實路徑 os.path.relpath(path[, start]) #從start開始計算相對路徑 os.path.samefile(path1, path2) #判斷目錄或文件是否相同 os.path.sameopenfile(fp1, fp2) #判斷fp1和fp2是否指向同一文件 os.path.samestat(stat1, stat2) #判斷stat tuple stat1和stat2是否指向同一個文件 os.path.split(path) #把路徑分割成dirname和basename,返回一個元組 os.path.splitdrive(path) #一般用在windows下,返回驅動器名和路徑組成的元組 os.path.splitext(path) #分割路徑,返回路徑名和文件擴展名的元組 os.path.splitunc(path) #把路徑分割為加載點與文件 os.path.walk(path, visit, arg) #遍歷path,進入每個目錄都調用visit函數,visit函數必須有 3個參數(arg, dirname, names),dirname表示當前目錄的目錄名,names代表當前目錄下的所有 文件名,args則為walk的第三個參數 os.path.supports_unicode_filenames #設置是否支持unicode路徑名

os.pardir #當前目錄的父目錄

os.path.join(script_dir, os.pardir, os.pardir) #script_dir的祖父目錄,例如:script_dir是F:\1\2\3,那麽os.path.join(script_dir, os.pardir, os.pardir)是F:\1\2\3\..\..

os.path.abspath(os.path.join(script_dir, os.pardir, os.pardir)) #script_dir的祖父目錄,例如:script_dir是F:\1\2\3,那麽os.path.abspath(os.path.join(script_dir, os.pardir, os.pardir))是F:\1

os 模塊提供了一個統一的操作系統接口函數, 這些接口函數通常是平臺指定的,os 模塊能在不同操作系統平臺如 nt 或 posix中的特定函數間自動切換,從而能實現跨平臺操作

1.文件操作

build-in函數 open 實現文件創建, 打開, 修改文件的操作

import os

import string

def replace(file, search_for, replace_with):

# replace strings in a text file

back = os.path.splitext(file)[0] + ".bak"

temp = os.path.splitext(file)[0] + ".tmp"

try:

# remove old temp file, if any

os.remove(temp)

except os.error:

pass

fi = open(file) #

fo = open(temp, "w") #

for s in fi.readlines():

fo.write(string.replace(s, search_for, replace_with))

fi.close()

fo.close()

try:

# remove old backup file, if any

os.remove(back)

except os.error:

pass

# rename original to backup...

os.rename(file, back)

# ...and temporary to original

os.rename(temp, file)

# try it out!

file = "c:\samples\sample.txt"

replace(file, "hello", "tjena")# search for the string ‘hello‘ and replace with ‘tjena

replace(file, "tjena", "hello")

2. 目錄操作

os 模塊包含了許多對目錄操作的函數

listdir 函數返回給定目錄下的所有文件(包括目錄)

import os

for file in os.listdir("c:\qtest"):

print file

getdir 獲取當前目錄

chdir 改變當前路徑

cwd = os.getcwd()

print "1", cwd

# go down

os.chdir("c:\qtest")

print "2", os.getcwd()

# go back up

os.chdir(os.pardir)#返回當前目錄的父目錄

print "3", os.getcwd()

makedirs removedirs 生成和刪除目錄

makedirs可以生成多層遞歸目錄, removedirs可以刪除多層遞歸的空目錄,若目錄中有文件則無法刪除

import os

os.makedirs("c:\\test\\multiple\\levels")

fp = open("c:\\test\\multiple\\levels\\file.txt", "w")

fp.write("inspector praline")

fp.close()

# remove the file

os.remove("c:\\test\\multiple\\levels\\file.txt")

# and all empty directories above it

os.removedirs("c:\\test\\multiple\\levels")

mkdir 和 rmdir只能處理單級目錄操作.

若要刪除非空目錄, 可使用 shutil模塊中的rmtree函數

3. 文件屬性的操作

import os

import time

file = ‘c:\qtest\editor.pyc‘

st = os.stat(file)

print "state", file

def dump(st):

mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime = st

print "- size:", size, "bytes"

print "- owner:", uid, gid

print "- created:", time.ctime(ctime)

print "- last accessed:", time.ctime(atime)

print "- last modified:", time.ctime(mtime)

print "- mode:", oct(mode)

print "- inode/dev:", ino, dev

print dir(st)

print

dump(st)

# print

fp = open(file)

st = os.fstat(fp.fileno())

print "fstat", file

dump(st)

os.path等os模塊函數