Python的OS模块
os.sep 可以取代操作系统特定的路径分隔符。windows下为 '\\'
os.name 字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是 'posix'
os.getcwd() 函数得到当前工作目录,即当前Python脚本工作的目录路径
os.getenv() 获取一个环境变量,如果没有返回none
os.putenv(key, value) 设置一个环境变量值
os.listdir(path) 返回指定目录下的所有文件和目录名
os.remove(path) 函数用来删除一个文件
os.system(command) 函数用来运行shell命令
os.linesep 字符串给出当前平台使用的行终止符。 例如:Windows使用 '\r\n',Linux使用 '\n' 而Mac使用 '\r'
os.path.split(path) 函数返回一个路径的目录名和文件名。 例如:('I:\\PlayGround\\sp', 'IMG_0001.txt')
os.path.isfile() 和os.path.isdir() 函数分别检验给出的路径是一个文件还是目录
os.path.exists() 函数用来检验给出的路径是否真地存在
os.curdir 返回当前目录 ('.')
os.mkdir(path) 创建一个目录
os.makedirs(path) 递归的创建目录
os.chdir(dirname) 改变工作目录到dirname
os.path.getsize(name) 获得文件大小,如果name是目录返回0L
os.path.abspath(name) 获得绝对路径
os.path.normpath(path) 规范path字符串形式
os.path.splitext() 分离文件名与扩展名
os.path.join(path,name) 连接目录与文件名或目录
os.path.basename(path) 返回文件名
os.path.dirname(path) 返回文件路径
os.walk(top,topdown=True,onerror=None) 遍历迭代目录
两个简单的例子:
1.遍历某一文件夹
1 def listdir(leval,path): 2 for i in os.listdir(path): 3 print('| '*(leval + 1) + i) 4 if os.path.isdir(path+i): 5 listdir(leval+1, path+i) 6 7 8 9 dstDirPath = 'I:' 10 11 listdir(0, dstDirPath +os.sep)
2.将某一文件夹下的txt的内容写到一个txt下
1 def ComFiles(srcdir, prefix): 2 srcfiles = os.listdir(srcdir+'/sp') 3 index = 1 4 for srcfile in srcfiles: 5 tempFile = open(srcdir+'/sp/'+srcfile,'r+') 6 for line in tempFile: 7 GatherFile.write(line) 8 9 #srcfilename = os.path.splitext(srcfile)[0][1:] 10 #sufix = os.path.splitext(srcfile)[1] 11 #destfile = srcdir + "//" + prefix + "_%04d"%(index) + sufix 12 #srcfile = os.path.join(srcdir, srcfile) 13 #os.rename(srcfile, destfile) 14 index += 1 15 16 srcdir = "I://PlayGround" 17 prefix = "IMG" 18 19 GatherFile = open(srcdir + "/Gather.txt",'w+') 20 ComFiles(srcdir, prefix) 21 GatherFile.close() 22 GatherFile = open(srcdir + "/Gather.txt",'r')
3.修改目录下的所有文件名
import sys, string, os, shutil #输入目录名和前缀名,重命名后的名称结构类似prefix_0001 def RenameFiles(srcdir, prefix): srcfiles = os.listdir(srcdir) index = 1 for srcfile in srcfiles: srcfilename = os.path.splitext(srcfile)[0][1:] sufix = os.path.splitext(srcfile)[1] #根据目录下具体的文件数修改%号后的值,"%04d"最多支持9999 destfile = srcdir + "//" + prefix + "_%04d"%(index) + sufix srcfile = os.path.join(srcdir, srcfile) os.rename(srcfile, destfile) index += 1 srcdir = "D://" prefix = "a" RenameFiles(srcdir, prefix)