>>> import os 導入模塊
>>> os.listdir("d://python25") 列出所有目錄和文件
['w9xpopen.exe', 'README.txt', 'NEWS.txt', 'LICENSE.txt', 'python.exe', 'pythonw.exe', 'Lib', 'DLLs', 'include', 'libs', 'tcl', 'Tools', 'Doc', 'odbchelper.py', 'odbchelper.pyc', 'test.log', 'sqlConnection.py', 'sqlConnection.pyc']
>>> dirname="d://python25" 支持自定義
>>> os.listdir(dirname)
['w9xpopen.exe', 'README.txt', 'NEWS.txt', 'LICENSE.txt', 'python.exe', 'pythonw.exe', 'Lib', 'DLLs', 'include', 'libs', 'tcl', 'Tools', 'Doc', 'odbchelper.py', 'odbchelper.pyc', 'test.log', 'sqlConnection.py', 'sqlConnection.pyc']
>>> [f for f in os.listdir(dirname) 篩選出一個list,存放filename
if os.path.isfile(os.path.join(dirname, f))]
['w9xpopen.exe', 'README.txt', 'NEWS.txt', 'LICENSE.txt', 'python.exe', 'pythonw.exe', 'odbchelper.py', 'odbchelper.pyc', 'test.log', 'sqlConnection.py', 'sqlConnection.pyc']
>>> [f for f in os.listdir(dirname) 篩選出一個list,存放dirname
if os.path.isdir(os.path.join(dirname, f))]
['Lib', 'DLLs', 'include', 'libs', 'tcl', 'Tools', 'Doc']
判別的應用
>>> os.path.isdir("D://")
True
>>> os.path.isdir("D://python25//odbchelper.py")
False
>>> os.path.isfile("D://python25//odbchelper.py")
True
當前目錄
>>> os.getcwd()
'D://Python25'
通配符的使用,引入glob
IDLE 1.2.1
>>> import glob
>>> glob.glob('D://python25//*.exe')
['D://python25//w9xpopen.exe', 'D://python25//python.exe', 'D://python25//pythonw.exe']
>>> glob.glob('D://python25//py*.exe')
['D://python25//python.exe', 'D://python25//pythonw.exe']
>>>