Learning Python(1)--操作文件和目录
来源:互联网 发布:招商银行java 编辑:程序博客网 时间:2024/06/01 10:03
Keynote
- os模块的重要函数或变量:
os.name
,操作系统类型。(linux->posix,windows->nt)os.uname()
,详细系统信息。(windows不支持此函数)os.environ
,环境变量;os.environ.get(‘key’),获得某个环境变量的值。
操作文件和目录:os.path.abspath('.')
,查看当前目录的绝对路径。os.path.join('/Users/michael', 'testdir')
,在某个目录下创建一个新目录,首先把新目录的完整路径表示出来。os.mkdir('/Users/michael/testdir')
,然后创建一个目录。os.rmdir('/Users/michael/testdir')
,删除一个目录。os.path.split('/Users/michael/testdir/file.txt')
,拆分一个路径,后一部分总是最后级别的目录或文件名。os.path.splitext('/path/to/file.txt)
,获取文件的扩展名。os.rename('tset.txt','test.py')
,对文件重命名。os.remove('test.py')
,删除文件。
过滤文件:os.listdir('.')
,列出当前目录下的所有目录和文件。os.path.isdir(x)
,x是否为目录。os.path.isfile(x)
,x是否为文件。
- Exercise:
编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。
-*— coding:utf-8 -*-import osdef search_file(filename,path='.'): content=os.listdir(path) file_list=list() dir_list=list() for x in content: if os.path.isdir(os.path.join(path,x)): dir_list.append(x) elif os.path.isfile(os.path.join(path,x)): file_list.append(x) for x in file_list: if filename==x: print(os.path.join(path,filename)) for x in dir_list: search_file(filename,os.path.join(path,x))search_file('test.txt')
os.path.isdir(os.path.join(path,x))
os.path.isfile(os.path.join(path,x))
os.path.isdir(x),x必须为一个目录
参考:廖雪峰博客–操作文件和目录
0 0
- Learning Python(1)--操作文件和目录
- python 文件和目录操作
- python文件和目录操作
- python 操作文件和目录
- Python--操作文件和目录
- Python 文件和目录操作
- Python操作文件和目录
- python文件和目录操作
- python的文件操作和目录操作
- Python中的文件和目录操作
- Python中的文件和目录操作
- Python中的文件和目录操作
- Python中的文件和目录操作
- Python入门系列:文件和目录操作
- Python中的文件和目录操作
- Python中的文件和目录操作实现
- Python 之 操作文件和目录
- Python 文件和目录的操作
- C语言视频学习网站
- 二维几何基本模板
- 集合Properties的应用
- centos7防火墙配置
- javascript本地对象、内置对象和宿主对象
- Learning Python(1)--操作文件和目录
- String类型的toString()返回的是什么
- 子网掩码划分基础再学习
- 设计模式-单例模式
- UIKeyBinding
- 将NotPointerException扼杀在摇篮中!
- cocostudio 资源文件夹中目录中有标点的解决方法
- 一些计算机视觉企业方面的网站
- 灯开关