您的位置:首页 > 其它

os 模块

2015-11-19 23:13 232 查看

作用

用python来实现目录的创建、修改、遍历

os.mkdir( “path”)

创建 目录与linux中的mkdir命令效果一样

>>> os.mkdir("d1")
>>> os.mkdir("d1/d2") #不能直接在d1不存在的情况下直接建立多级目录
>>> os.mkdir("d1/d2/d3") #只能一步一步的建立
>>> os.listdir(".")
['d1']


os.makedirs(“path” )

创建目录且可以创建多级目录,与linux中的mkdir -p效果一样

#可以在没有a和b的情况下,直接建立多级目录
>>> os.makedirs("a/b/c")  #与mkdir -p a/b/c 一样


os.rmdir( “path”)和os.removedirs( “path”)

os.rmdir 删除目录

os.removedirs 删除目录,且可以删除多级目录

注意:不可以删除文件、若目录下有文件,不为空,也不能删除。

区别在于以下代码:

>>> os.makedirs("a/b/c")
os.rmdir("a/b/c")# 则只删除c,a和b目录保留
os.removedirs("a/b/c") #会把a b c目录全部删除


os.listdir( “path”)

获取当前路径下的所有文件和目录,与linux中的ls命令效果一样

>>> os.chdir("/tmp/os")
>>> os.listdir(".")
['d2', 'd1']


os.getcwd( )

获取当前目录,与linux中的pwd命令效果一样

>>> import os
>>> os.getcwd()
'/tmp/os'


os.chdir( “path”)

改变路径,与linux中的cd命令效果一样

>>> os.getcwd()
'/tmp/os'
>>> os.chdir("../..")
>>> os.getcwd()
'/'


os.walk(dir)

文件和文件夹遍历

tree

.

├── d1

│ ├── d11

│ ├── d12

│ ├── f11

│ └── f12

├── d2

│ ├── f21

│ └── f22

├── f1

├── f2

└── f3

#!/usr/bin/python
#coding:utf8
#

import os
import os.path

#遍历的文件夹
rootdir = "/tmp/d"

for parent,dirnames,filenames in os.walk(rootdir):
#parent: 父目录  每次循环返回是一个字符串
#dirnames: 父目录下面一层的文件夹名字(不含路径)  每次循环返回是一个list
#filenames: 父目录下面一层的文件名字(不含路径)  每次循环返回是一个list

#遍历rootdir下面所有的文件夹
for dirname in  dirnames:
print "parent is " + parent         #父目录 (含有路径)
print "dirname is " + dirname      #父目录下的文件夹 (不含有路径)
print os.path.join(parent, dirname) #
print "--"*30

for parent, dirnames,filenames in os.walk(rootdir):
#遍历rootdir下面所有的文件
for filename in filenames:
print "parent is :" + parent
print "filename is:" + filename
print "the full name of the file is:" + os.path.join(parent,filename) #输出文件路径信息
print "#"*30

#输出结果
parent is /tmp/d
dirname is d2
/tmp/d/d2
------------------------------------------------------------
parent is /tmp/d
dirname is d1
/tmp/d/d1
------------------------------------------------------------
parent is /tmp/d/d1
dirname is d12
/tmp/d/d1/d12
------------------------------------------------------------
parent is /tmp/d/d1
dirname is d11
/tmp/d/d1/d11
------------------------------------------------------------
parent is :/tmp/d
filename is:f3
the full name of the file is:/tmp/d/f3
##############################
parent is :/tmp/d
filename is:f2
the full name of the file is:/tmp/d/f2
##############################
parent is :/tmp/d
filename is:f1
the full name of the file is:/tmp/d/f1
##############################
parent is :/tmp/d/d2
filename is:f22
the full name of the file is:/tmp/d/d2/f22
##############################
parent is :/tmp/d/d2
filename is:f21
the full name of the file is:/tmp/d/d2/f21
##############################
parent is :/tmp/d/d1
filename is:f11
the full name of the file is:/tmp/d/d1/f11
##############################
parent is :/tmp/d/d1
filename is:f12
the full name of the file is:/tmp/d/d1/f12
##############################
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: