由于经常用python写脚本,将路径操作的一些api做了总结,方便以后查询
#!/usr/bin/python # -*- coding:UTF-8 -*- import os import sys import shutil # python路径操作整理 # 递归遍历文件夹 def listFiles(dirPath): fileList=[] for root,dirs,files in os.walk(dirPath): for fileObj in files: print fileObj return fileList # 获取当前路径文件夹 def cur_file_dir(): #获取脚本路径 path = sys.path[0] if os.path.isdir(path): return path elif os.path.isfile(path): return os.path.dirname(path) # 替换文本内容 def replaceStrInfile(filepath, oldStr, newStr): if os.path.exists(filepath) == False: print filepath + "不存在" sys.exit(1) input_file = open(filepath, 'r') lines = input_file.readlines() content = "" for line in lines: if oldStr in line: line = line.replace(oldStr, newStr) content += line input_file.close() try: out_file = open(filepath, "w") out_file.writelines(content) out_file.close() except Exception, e: print "没有权限" + filepath #path 为一个路径,输出,把path分成两部分,具体看实例: print os.path.split("abc/de.txt") #('abc', 'de.txt') print os.path.split("abc") #(", 'abc') #把文件名分成文件名称和扩展名 # os.path.splitext("abc/abcd.txt") # ('abc/abcd', '.txt') #把目录名提出来 print "dirName:"+os.path.dirname("user/abc") #输出为空 print "def dirName:"+os.path.dirname('def') #abc print "abc baseName:"+os.path.basename('abc') # abc print "user/abc.txt baseName:"+os.path.basename('user/abc.txt') # abc print os.path.basename('bcd/abc') # abc #这个需要注意不包括目录名称 print ". baseName: "+os.path.basename('.') #把文件src内容拷贝到文件dst中。,目标区域必须可以写,如果dst存在,则dst被覆盖 #shutil.copy("src","dst") #智能化地连接一个或多个路径组件。如果任一组件是一个绝对路径,所有前面的组件被丢弃(在 print os.path.join("abc","cds.txt") print os.path.join("abc","use/cds.txt","de") # 递归拷贝文件夹 def copytree(src, dst, symlinks=False): if os.path.exists(dst): shutil.rmtree(dst) names = os.listdir(src) if not os.path.isdir(dst): os.makedirs(dst) for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks) else: shutil.copy(srcname, dstname)