py中的目录与文件判别代码
python,创建文件夹
dirName=r"Item\Cash\0501.img\" import os
>>> os.makedirs(dirName)
>>> import os
>>> os.makedirs(r'd:/1/1')
>>> os.path.exists(r'd:/1/1')判断目录是否存在
True
>>>
os.getcwd()获取当前目录
列举当前目录下的所有文件
dirs=os.listdir('.')
for files in dirs:
if 'txt' in files and 'Zone_out' in files:
openfile=files
os.renames( old, new)文件重命名
>>> 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']
>>>
python遍历文件夹和文件
这个也许是最常用的功能,如下:
[复制此代码]CODE:
import os
import os.path
rootdir = "D:\\programmer\\training"
for parent, dirnames, filenames in os.walk(rootdir):
#case 1:
for dirname in dirnames:
print "parent is:" + parent
print "dirname is:" + dirname
#case 2
for filename in filenames:
print "parent is:" + parent
print "filename with full path :" + os.path.join(parent, filename)
解释说明:
1.os.walk返回一个三元组.其中dirnames是所有文件夹名字(不包含路径),filenames是所有文件的名字(不包含路径).parent表示父目录.
2.case1 演示了如何遍历所有目录.
3.case2 演示了如何遍历所有文件.
4.os.path.join(dirname,filename) : 将形如"/a/b/c"和"d.java"变成/a/b/c/d.java".
No comments:
Post a Comment