python os模块

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

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

os.sep 可以取代操作系统特定的路径分割符。
os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。
os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。
os.getenv()和os.putenv()函数分别用来读取和设置环境变量。
os.listdir()返回指定目录下的所有文件和目录名。
os.remove()函数用来删除一个文件。
os.system()函数用来运行shell命令。
os.mkdir()函数用来创建目录。
os.makedirs()函数用来创建目录,如果此路径中目录没有则自动创建,相当于linux下的mkdir -p。


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

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

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

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

os和os.path模块
os.listdir(dirname):列出dirname下的目录和文件
os.getcwd():获得当前工作目录
os.curdir:返回但前目录('.')
os.chdir(dirname):改变工作目录到dirname
os.umask(mask):设置当前文件权限掩码,并返回上一个权限掩码。
os.setsid():使独立于终端的进程(不响应sigint,sighup等),使脱离终端。


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):返回文件路径

------------------------------------------------------------------------------

写点东东,增加熟悉感

Code:


#!/usr/bin/python

import os

fadd = ("a.txt", "b.txt", "d/d.txt")
fdel = ("c.txt",)

InputPath = raw_input()
if(os.path.isdir(InputPath)==False):
print "you have input a incrrect path"
else:
os.chdir(InputPath)
bf = os.listdir(InputPath)
for f in fadd:
(dr, fl) = os.path.split(f)
ndr = os.getcwd()+"\"
if(dr!=""):
ndr = ndr+dr+"\"
os.mkdir(ndr)
os.chdir(ndr)
hf = file(ndr+fl, 'w')
hf.close()
os.chdir(InputPath)
for f in fdel:
os.remove(f)
af = os.listdir(InputPath)



from:http://hi.baidu.com/happynp/blog/item/729243f902d5a751242df2c2.html

posted @ 2011-02-12 01:01  dkcndk  阅读(1136)  评论(0编辑  收藏  举报