python中文件的遍历、拷贝以及几个版本的小区别
2012-05-16 13:45
369 查看
这几天需要对实验室集群中机器的数据进行处理,借此机会熟悉下python这个语言。实验室集群中机器各异,python版本也很多样化,总共有四个版本。写的程序调成了三种样子,才得以在各个机器上跑完。记录下常用的代码。
一个在2.7中可以运行的代码:
os.walk() 较低版本的python不支持,所以写了一个在2.2中可以运行的代码,如果在2.3中运行,需要去掉第一句话:
一个在2.7中可以运行的代码:
import glob import os import shutil import re outlinkPath="/POOL_Temp_space/xzm/run/" putPosition="/POOL_Temp_space/lyn/infoMall/allOutlinksFile/" def fun(path): #path为要遍历的顶端目录路径 patt=re.compile(r'outlinks.\d+$') fileList=[] for root, dirs, files in os.walk(outlinkPath): for fn in files: if patt.match(fn): #用正则表达式筛选文件名 fileList.append(root+"/"+fn) return fileList #返回完整文件路径列表 fileList=fun(outlinkPath) for filePath in fileList: fileName='' for c in filePath: if not (c.isalpha() or c.isdigit()): fileName+='_' else: fileName+=c if not os.path.exists(putPosition): os.makedirs(putPosition) open(putPosition+fileName,'w') #2.7中可以不用这句,下一局会自动建立文件,但是2.6中需要在没有此文件时先建立下 shutil.copyfile(filePath,putPosition+fileName) #将filePath文件拷贝到相应位置
os.walk() 较低版本的python不支持,所以写了一个在2.2中可以运行的代码,如果在2.3中运行,需要去掉第一句话:
from __future__ import generators #2.2需要加此句才可以用yield,更高版本的不用此句 import glob import os import shutil import re import sys outlinkPath="/POOL_Temp_space/xzm/run/" putPosition="/POOL_Temp_space/lyn/infoMall/allOutlinksFile/" fileList=[] def walktree(top = ".", depthfirst = True): #递归的遍历 try: import stat, types names = os.listdir(top) if not depthfirst: yield top, names for name in names: try: st = os.lstat(os.path.join(top, name)) except os.error: continue if stat.S_ISDIR(st.st_mode): for (newtop, children) in walktree (os.path.join(top, name), depthfirst): yield newtop, children if depthfirst: yield top, names except os.error: yield top, [] patt=re.compile('outlinks.\d+$') if not os.path.exists(putPosition): os.makedirs(putPosition) for top, names in walktree(outlinkPath):#遍历生成的文件元组 for name in names: filePath=top+'/'+name if not patt.match(name): continue fileName='' for c in filePath: if not (c.isalpha() or c.isdigit()): fileName+='_' else: fileName+=c open(putPosition+fileName,'w') shutil.copyfile(filePath,putPosition+fileName)
相关文章推荐
- [Tool] Python几个windows版本的区别
- 好吧我承认最近一直入门python! 关于python3 和 python2 List 的一点区别 以及python 通过enumerate 内建函数遍历List
- Cocos2d-x教程(19)-cocos2d-x.xcodeproj-2.2.x版本对cocos2dx文件的引用以及Cocos2d-x 2.2.0版本后项目拷贝出来无法运行的原因
- Cocos2d-x教程(19)-cocos2d-x.xcodeproj-2.2.x版本对cocos2dx文件的引用以及Cocos2d-x 2.2.0版本后项目拷贝出来无法运行的原因
- 关于python安装的几个版本的区别
- Python读写,以及修改my.ini文件--针对Python3.0版本
- Python 中当前位置以及目录文件遍历操作
- Python 如何遍历文件夹以及子文件夹下的所有文件
- ~/.bashrc, ~/.bash_profile 以及/etc/profile /etc/bashrc 几个文件的区别与相互关系
- Java递归遍历删除拷贝文件以及获取文件夹大小
- python简单目录遍历和文件拷贝
- 路径遍历与文件读取漏洞以及其修复方案
- 如何拷贝指定类型的文件以及如何更改拷贝的文件的扩展名
- java遍历某个文件夹下的所有文件 以及删除所有文件
- Python 使用os模块遍历文件目录
- Linux下的几个配置文件以及启动先后顺序
- python .py .pyc .pyw 文件有什么区别
- Python socket收发文件以及二进制文件打包
- python 中xrange 和range的用法区别 以及yield的用法
- python文件打开方式详解——a、a+、r+、w+区别