python 文件目录操作

在Python程序中执行目录和文件的操作

Python内置的os模块可以直接调用操作系统提供的接口函数

Python交互式命令行

>>> import os
>>> os.name # 操作系统类型
'posix'
如果是posix,说明系统是Linux、Unix或Mac OS X,如果是nt,就是Windows系统。

合并、拆分路径的函数并不要求目录和文件要真实存在,它们只对字符串进行操作

 


用Python的特性来过滤文件

列出当前目录下的所有目录:

>>> [x for x in os.listdir('.') if os.path.isdir(x)]
['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Applications', 'Desktop', ...]


要列出所有的.py文件:

>>> [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
['apis.py', 'config.py', 'models.py', 'pymonitor.py', 'test_db.py', 'urls.py', 'wsgiapp.py']


编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。
def findFile(str, path='.'):
for f in os.listdir(path):
fPath = os.path.join(path, f)
if os.path.isfile(fPath) and str in f:
print(fPath)
if os.path.isdir(fPath):
findFile(str, fPath)

posted @ 2018-03-01 09:58  夜游星  阅读(187)  评论(0编辑  收藏  举报