pythonのファイルの遍歴、コピー、およびいくつかのバージョンの小さな違い
9300 ワード
ここ数日、実験室クラスタ内のマシンのデータを処理する必要があり、pythonという言語を熟知する必要があります.実験室クラスタでは機械が異なり,pythonバージョンも多様化し,合計4つのバージョンがある.書いたプログラムは三つの形になって、やっと各機械で走ることができた.よく使うコードを記録します.
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)