python路径操作常用方法
来源:互联网 发布:javascript onclick 编辑:程序博客网 时间:2024/06/07 07:50
由于经常用python写脚本,将路径操作的一些api做了总结,方便以后查询
#!/usr/bin/python# -*- coding:UTF-8 -*-import osimport sysimport 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')#abcprint "abc baseName:"+os.path.basename('abc')# abcprint "user/abc.txt baseName:"+os.path.basename('user/abc.txt')# abcprint 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)
0 0
- python路径操作常用方法
- python 常用方法-路径处理
- Python文件操作的常用方法
- python---集合set常用方法和操作
- 文件路径常用操作
- python路径常用函数
- python 的路径操作
- python路径操作
- python 的路径操作
- 常用路径、方法总结
- Memcached 安装、使用(Python操作)以及常用方法
- python里的字符串常用内置方法和格式化操作
- Python列表操作和字符串的常用方法
- python操作mysql数据库的常用方法使用详解
- python---字典dict的常用方法和操作
- VC 文件路径常用操作
- 常用的操作路径函数
- Python:os.path路径操作
- java 线程及synchronized关键字
- U-21
- mybatis+oracle配置文件
- 495. Teemo Attacking
- 删除或修改本地Git保存的账号密码
- python路径操作常用方法
- 第六届蓝桥杯加法变乘法
- Apache POI介绍
- java--08--多线程(三)
- 2016 EC-Final Problem D. Ice Cream Tower(二分+贪心)
- codeforces 672D D. Robin Hood (二分+思维)
- EJBCA简介
- 蓝桥杯算法提高 矩阵乘法
- Pixhawk原生固件PX4之顶层软件结构