Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26253732
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Python/Ruby

2009-04-29 13:38:32

Python中常用模块os整理

[整理人:遥方 整理时间:2010-3-20]

Python的标准库中的os模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在LinuxWindows下运行。

下面列出了一些在os模块中比较有用的部分。它们中的大多数都简单明了。

1.     os.sep 可以取代操作系统特定的路径分割符。

2.     os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'

3.     os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。

4.     os.getenv()os.putenv()函数分别用来读取和设置环境变量。

5.     os.listdir()返回指定目录下的所有文件和目录名。

6.     os.remove()函数用来删除一个文件。

7.     os.system()函数用来运行shell命令。

8.     os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n'Linux使用'\n'Mac使用'\r'

9.     os.path.split()函数返回一个路径的目录名和文件名。

10.  os.path.isfile()os.path.isdir()函数分别检验给出的路径是一个文件还是目录。

11.  os.path.existe()函数用来检验给出的路径是否真地存在

osos.path模块
os.listdir(dirname)
:列出dirname下的目录和文件
os.getcwd()
:获得当前工作目录
os.curdir:
返回当前目录('.')
os.chdir(dirname):
改变工作目录到dirname

os.path.isdir(name):
判断name是不是一个目录,name不是目录就返回false
os.path.isfile(name):
判断name是不是一个文件,不存在name也返回false
os.path.exists(name):
判断是否存在文件或目录name
os.path.getsize(name):
获得文件大小,如果name是目录返回0L
os.path.abspath(name):获得绝对路径
os.path.normpath(path):
规范path字符串形式
os.path.split(name):
分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)
os.path.splitext():
分离文件名与扩展名
os.path.join(path,name):
连接目录与文件名或目录
os.path.basename(path):
返回文件名
os.path.dirname(path):
返回文件路径

 

 

 

 

以下是一些常用的代码

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)

 

阅读(1208) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~