您的位置:首页 > 编程语言 > Python开发

Python中的OS模块

2010-05-19 17:37 323 查看
os模块提供了多数操作系统的功能接口函数.当os模块被导入后,它会自适应于不同的操作系统平台,如posix或NT系统平台,os模块会根据不同的平台进行相应的操作.本节内容将对os模块提供的函数进行详细的解读.

1.1 文件操作函数

1.1.1 open()函数提供创建、打开、修改文件的功能。

Example 1-1. Using the os Module to Rename and Remove Files

#Filename: os-example-1.py
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 = "samples/sample.txt"
replace(file, "hello", "tjena")
replace(file, "tjena", "hello")

1.1.2 rename()和remove()函数,对文件进行重命名和删除操作.请参照例1-1

1.2 目录操作

1.2.1 listdir()函数,返回指定目录下所有文件名,并保存于一列表中.但当前目录标记(.)和父目录标记(..)不在其中.

Example 1-2. Using the os Module to List the Files in a Directory

File: os-example-2.py
import os
for file in os.listdir("samples"):
print file

1.2.2 getcwd()和chdir()函数,功能是获取和改变当前工作目录.

Example 1-3. Using the os Module to Change the Working Directory

#Filename: os-example-3.py
import os
# where are we?
cwd = os.getcwd()
print "1", cwd
# go down
os.chdir("samples")
print "2", os.getcwd()
# go back up
os.chdir(os.pardir)
print "3", os.getcwd()

1.2.3 mkdir(),rmdir(),makedirs()和removedirs()函数用于创建和删除目录操作.mkdir,rmdir和makedirs,removedir的不同在于前者只创建和删除一级目录,而后者则能创建和删除多级目录.要删除非空目录则要用到shutil模块中的rmtree()函数,在shutil模块详解中有介绍.

Example 1-4. Create and Remove Multiple Directory Levels

#Filename: os-example-4.py
import os
os.makedirs("test/multiple/levels")
fp = open("test/multiple/levels/file", "w")
fp.write("inspector praline")
fp.close()
# remove the file
os.remove("test/multiple/levels/file")
# and all empty directories above it
os.removedirs("test/multiple/levels")

1.3 文件属性操作

1.3.1stat()函数返回一个文件的所有属性,所有的属性都包含在一个元组中.而fstat()函数则返回一个已经打开的文件的所有属性.

Example 1-32. Get Information About a File

File: os-example-1.py
import os
import time
file = "samples/sample.jpg"
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
# get stats for a filename
st = os.stat(file)
print "station", file
dump(st)
print st

# get stats for an open file
fp = open(file)
st = os.fstat(fp.fileno())
print "fstat", file
dump(st)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: