您的位置:首页 > 编程语言 > Python开发

python中文件的遍历、拷贝以及几个版本的小区别

2012-05-16 13:45 369 查看
这几天需要对实验室集群中机器的数据进行处理,借此机会熟悉下python这个语言。实验室集群中机器各异,python版本也很多样化,总共有四个版本。写的程序调成了三种样子,才得以在各个机器上跑完。记录下常用的代码。

一个在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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: