Python学习:IO基础(2):对文件目录的操作

来源:互联网 发布:淘宝lite下载 编辑:程序博客网 时间:2024/05/16 06:48

[0]:操作文件和目录:Python的os模块和os.path模块提供了许多操作系统的接口。首先看一下怎么列出指定目录下的指定文件:

只需要一行代码,需要强调的是用isfile或者isdir进行判断的时候要将全部的路径都添加进行.

[x for x in os.listdir('E:/code/') if os.path.isdir(os.path.join('E:/code/',x))]

[1]如果需要对文件的路径进行分割或者合并,应该使用path模块的join函数和split函数,因为不同操作系统的路径分割符是不一样的,这个模块的函数会搞定一切.

>>> os.path.abspath('.')'/Users/michael'# 在某个目录下创建一个新目录,首先把新目录的完整路径表示出来:>>> os.path.join('/Users/michael', 'testdir')'/Users/michael/testdir'# 然后创建一个目录:>>> os.mkdir('/Users/michael/testdir')# 删掉一个目录:>>> os.rmdir('/Users/michael/testdir')

[2]注意,有些函数比如复制文件的函数式在shutil模块里面的,这可以看作是os的一个补充.

[3]练习:寻找指定目录下的所有带有指定名字的文件.

import osdef search_files(abspath,name):    dirlist = os.listdir(abspath)#get all dir or files    for possibles in dirlist:        path = os.path.join(abspath,possibles)        if(os.path.isfile(path)):            if(name in possibles):print(os.path.join(abspath,possibles))        else:search_files(path,name)search_files('E:\code\\','text')

还可以用内置的函数walk来遍历所有目录与文件,walk用类似于深度优先的方式进行遍历.

import osdef search_files(abspath,name):    for x in os.walk(abspath):        for y in x[2]:            if(name in y):print(y)search_files('E:/code/','text')
0 0
原创粉丝点击