常用的module是 os ,os.path 和shutil,所以要先引入他们.
python遍历文件夹和文件
这个也许是最常用的功能,如下:
代码如下:
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)
代码如下:
import os.path
spath="D:/download/flight/flighthtml.txt"
# case 1:
p,f=os.path.split(spath);
print "dir is:"+p
print "file is:"+f
# case 2:
drv,left=os.path.splitdrive(spath);
print "driver is:"+drv
print "left is:"+left
# case 3:
f,ext=os.path.splitext(spath);
print "f is:"+f
print "ext is:"+ext