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

python,os中的文件操作

2013-12-11 21:40 267 查看
1.os.walk(root,topdown=True,onerror=None)

返回:root,dirs,files

root为当前处理路径,dirs为root下的文件夹,files为root下的文件

a = os.walk(‘.’)

for i in a:
print i

输出:
(‘.’, ['abc', 'temp'], ['path0704.py', '\xc2\xb7\xbe\xb6\xcf\xe0\xb9\xd8\xd1\xa7\xcf\xb0.txt'])
(‘.\\abc’, [], ['\xd0\xc2\xbd\xa8 BMP \xcd\xbc\xcf\xf1.bmp'])
(‘.\\temp’, ['temp1'], ['temp.h'])(‘.\\temp\\temp1′, [], ['abc.bmp'])


2.os.path.walk(top,func,arg)

func是回调函数,第1个参数为walk()的参数tag,第2个参数表示当前处理的目录,第3个参数表示当前处理目录的文件列表

故而,此函数无法返回dirs

def callback(arg,directory, files):
print directory,
print files,
print arg
print ‘——————–’

os.path.walk(‘.’,callback, ’123456′)

输出:
. ['path0704.py', 'temp', '\xc2\xb7\xbe\xb6\xcf\xe0\xb9\xd8\xd1\xa7\xcf\xb0.txt'] 123456
——————–
.\temp ['temp.h', 'temp1'] 123456
——————–
.\temp\temp1 ['abc.bmp'] 123456


os.path

os.path 模块中的路径名访问函数

1.分隔
basename() 去掉目录路径, 返回文件名

dirname() 去掉文件名, 返回目录路径

join() 将分离的各部分组合成一个路径名

split() 返回(dirname(), basename()) 元组

splitdrive() 返回(drivename, pathname) 元组

splitext() 返回(filename, extension) 元组

2.信息
getatime() 返回最近访问时间

getctime() 返回文件创建时间

getmtime() 返回最近文件修改时间

getsize() 返回文件大小(以字节为单位)

3.查询
exists() 指定路径(文件或目录)是否存在

isabs() 指定路径是否为绝对路径

isdir() 指定路径是否存在且为一个目录

isfile() 指定路径是否存在且为一个文件

islink() 指定路径是否存在且为一个符号链接

ismount() 指定路径是否存在且为一个挂载点

samefile() 两个路径名是否指向同个文件

例子:

os.path.split(path)

返回:把path分成两部分
print os.path.split(“abc/de.txt”)
(‘abc’, ‘de.txt’)

os.path.splitext(filename)

把文件名分成文件名称和扩展名
os.path.splitext(abc/abcd.txt)
(‘abc/abcd’, ‘.txt’)


os.path.dirname(path)

把目录名提出来
print os.path.dirname(“abc”)
#输出为空
print os.path.dirname(‘abc\def’)
abc


os.path.basename(filename)

取得主文件名
print os.path.basename(‘abc’)
abc
print os.path.basename(‘abc.txt’)
abc
print os.path.basename(‘bcd/abc’)
abc #这个需要注意不包括目录名称
print os.path.basename(‘.’)
.

os模块

os 模块属性
linesep 用于在文件中分隔行的字符串

sep 用来分隔文件路径名的字符串

pathsep 用于分隔文件路径的字符串

curdir 当前工作目录的字符串名称

pardir (当前工作目录的)父目录字符串名称

函数
1.重命名:os.rename(old, new)

2.删除:os.remove(file) #删除一个文件,一定是一个文件

3.列出目录下的文件:os.listdir(path)

4.获取当前工作目录:os.getcwd()

5.改变工作目录:os.chdir(newdir)

6.创建多级目录:os.makedirs(r"c:\python\test") #可以创建多级目录

7.创建单个目录:os.mkdir("test") #path为目录名: 这里有个要求,只能创建一级目录 比如path为 abc/def 则当前目录下必须存在abc 否则失败

8.删除多个目录:os.removedirs(r"c:\python") #删除所给路径最后一个目录下所有空目录。

9.删除单个目录:os.rmdir("test") #删除一个目录,而且一定为空,否则os.errer

10.获取文件属性:os.stat(file)

11.修改文件权限与时间戳:os.chmod(file)

12.执行操作系统命令:os.system("dir")

13.启动新进程:os.exec(), os.execvp()

14.在后台执行程序:os.spawnv()

15.终止当前进程:os.exit(), os._exit()

16.是否为根文件目录:os.ismount("c:\\") --> True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: