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

python中OS模块操作文件和目录

2017-04-01 15:09 746 查看
在python中执行和操作目录和文件的操作是通过内置的python OS模块封装的函数实现的。

首先导入模块,并查看操作系统的类型:

>>> import os
os.name # 操作系统类型
'nt'


nt
,是
Windows
;posix是Linux或者unix

1、对目录和文件的操作。

>>> os.path#查看当前工作路径
<module 'ntpath' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\ntpath.py'>

>>> os.path.abspath('.')#查看当前工作的绝对路径
'C:\\Users\\Administrator\\Desktop\\enen\\python'

>>> os.path.join('C:\\Users\\Administrator\\Desktop\\enen\\python','dede')#在当前目录下新建一个文件夹,并将文件路径显示出来
'C:\\Users\\Administrator\\Desktop\\enen\\python\\dede'

>>> os.mkdir('C:\\Users\\Administrator\\Desktop\\enen\\python\\test')#创建一个目录

>>> os.rmdir('C:\\Users\\Administrator\\Desktop\\enen\\python\\test')#删除一个目录。
>>> #注意,Windows和Linux环境下路径表示有所差异


2、对目录文件路径拆分

>>> os.path.split('C:\\Users\\Administrator\\Desktop\\enen\\python\\test.txt') #对当前文件路径拆分
('C:\\Users\\Administrator\\Desktop\\enen\\python', 'test.txt')
>>> os.path.split('C:\\Users\\Administrator\\Desktop\\enen\\python\\te.txt')#对当前不存在的文件路径进行拆分
('C:\\Users\\Administrator\\Desktop\\enen\\python', 'te.txt')
>>>


>>> os.path.splitext('C:\\Users\\Administrator\\Desktop\\enen\\python\\test.txt')#使用splitext进行路径拆分
('C:\\Users\\Administrator\\Desktop\\enen\\python\\test', '.txt')


以上注意两点:a.合并、拆分路径的函数并不要求目录和文件要真实存在,它们只对字符串进行操作,例如演示代码所示。b.使用splitext()进行拆分可以直接得到文件的扩展名。

3、复制文件的函数在os模块中没有提供,可以使用shutil模块中的copyfile()函数进行操作。它是os模块的补充。有关shutil模块中函数的调用http://www.jb51.net/article/87984.htm

4、对当前目录文件进行的筛选:

>>> [x for x in os.listdir('.') if os.path.isdir(x)]#使用列表生成式,并使用if进行判断,os.listdir可以列出文件和目录,os.path.isdir()函数判断某一路径是否为目录。
['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Applications', 'Desktop', ...]


>>> [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']#筛选出扩展名是py的所有文件,语法使用很是精巧,对当前拆分的文件路径进行索引判断,返回py扩展名的文件。
['apis.py', 'config.py', 'models.py', 'pymonitor.py', 'test_db.py', 'urls.py', 'wsgiapp.py']


学习廖老师教程做的笔记。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: