python 檔案、目錄屬性的操作os.path等os模組函式
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))
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.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)
dump(st)
fp = open(file)
st = os.fstat(fp.fileno())
print "fstat", file
dump(st)
remark: os.stat(path/file)返回檔案的對應屬性值st_mode (protection bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid (user id of owner), st_gid (group id of owner), st_size (size of file, in bytes), st_atime (time of most recent access), st_mtime (time of most recent content modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows):
os.fstat(path/file)
Return status for file descriptor fd, like stat().