一、前言
作為一個全棧工程師,必須要熟練掌握各種語言。。。HelloWorld。最近就被“逼着”走向了python開發之路,大體實現的功能是寫一個通用類庫將服務器本地存儲的文件進行簡單清洗后轉儲到HDFS中,所以基本上python的相關知識都涉及到了,這里對一些基礎操作以及hdfs操作做一總結,以備查閱。
二、基礎操作
2.1 字符串操作
字符串操作應該是所有語言的基礎。python基本上也提供了其他語言常用的一些字符串處理函數,常用的如下:
1、startswith 以某個字符串起始
2、endswith 以某個字符串結尾
3、contain python沒有提供contain函數,可以使用 'test' in somestring 的方式來進行判斷,當然也可以使用index來判斷
4、strip 去除空格及特殊符號
5、len 判斷字符串長度len(str)
6、upper lower 大小寫轉換
7、split 分隔字符串
2.2 文件操作
文件以及文件夾操作也是寫程序中經常用到的功能。python中文件操作常用的有以下函數。
1、walk 用於遞歸遍歷文件夾,獲取所有文件。
2、os.path 文件、文件夾路徑等操作。
對文件操作進行了簡單的封裝,代碼如下,僅供參考:
def isFile(name): return os.path.isfile(name) def isDir(name): return os.path.isdir(name) def getDirPath(filename): return os.path.dirname(filename) def getFilename(path): return os.path.basename(path) def getExt(filename): return os.path.splitext(filename)[1] def changeExt(filename, ext): if not ext.startswith('.'): ext = '.' + ext return getFilenameWithoutExt(filename) + ext def getDirAndFileNameWithoutExt(filename): return os.path.splitext(filename)[0] def getFilenameWithoutExt(filename): return getFilename(getDirAndFileNameWithoutExt(filename)) def deleteFileOrFolder(path): try: if isFile(path): os.remove(path) elif isDir(path): shutil.rmtree(path) # or os.rmdir(path) except: pass
2.3 壓縮解壓縮操作
可以參考http://blog.csdn.net/luoshengkim/article/details/46647423
1、tar.gz
壓縮、解壓.tar.gz文件可以直接使用tarfile包,首先引入:import tarfile。解壓縮操作如下:
tar = tarfile.open(path, 'r:gz') file_names = tar.getnames() for file_name in file_names: tar.extract(file_name, path) tar.close()
壓縮操作如下:
tar = tarfile.open(tarpath, 'w:gz') if isFile(srcpath): tar.add(srcpath, arcname=srcpath) elif isDir(srcpath): for root, dir, files in os.walk(srcpath): for file in files: fullpath = os.path.join(root, file) tar.add(fullpath, arcname=file) tar.close()
tarfile.open的mode有以下種,每種對應不同的方式,需要根據自己需要選取:
mode action
'r' or 'r:*' Open for reading with transparent compression (recommended). 'r:' Open for reading exclusively without compression. 'r:gz' Open for reading with gzip compression. 'r:bz2' Open for reading with bzip2 compression. 'a' or 'a:' Open for appending with no compression. The file is created if it does not exist. 'w' or 'w:' Open for uncompressed writing. 'w:gz' Open for gzip compressed writing. 'w:bz2' Open for bzip2 compressed writing.
2、gz
壓縮、解壓.gz文件可以直接使用gzip包,首先引入:import gzip。解壓縮操作如下:
fname = path.replace('.gz', '').replace('.GZ', '') gfile = gzip.GzipFile(path) open(fname, 'wb').write(gfile.read()) gfile.close()
壓縮操作如下:
gfile = gzip.GzipFile(srcpath + '.gz', mode='w') gfile.write(open(srcpath, 'rb').read()) gfile.close()
此處同樣需要注意mode的選取,並且還要注意解壓縮的時候創建解壓縮文件時的mode。
3、zip
壓縮、解壓.zip文件可以直接使用zipfile包,首先引入:import zipfile。解壓縮操作如下:
zip_file = zipfile.ZipFile(path, mode='r') for name in zipfile.namelist(): zip_file.extract(name, getFilenameWithoutExt(path)) zip_file.close()
壓縮操作如下:
zip_file = zipfile.ZipFile(zippath, mode='w') if isFile(srcpath): zip_file.write(srcpath, arcname=srcpath) elif isDir(srcpath): for root, dir, files in os.walk(srcpath): for file in files: fullpath = os.path.join(root, file) zip_file.write(fullpath, arcname=file) zip_file.close()
三、hdfs操作
hdfs操作采用hdfs3庫,這是c語言寫的libhdfs庫的python封裝版,基本能滿足常用的hdfs操作。
3.1 引入hdfs3
只需要知道namenode的地址以及端口號即可,代碼如下:
from hdfs3 import HDFileSystem hdfs = HDFileSystem(host='namenode', port=8020)
3.2 建立文件夾
如果想要上傳文件等到hdfs,必須保證其文件夾存在,否則會報錯,此時就可以先創建文件夾,只需要使用hdfs.mkdir(dir)即可,並且此命令會遞歸創建文件夾,即不需要一層層的創建不存在的文件夾。
3.3 上傳文件
上傳文件的時候只需要指定本地文件地址以及hdfs中存儲地址即可,hdfs地址也需要包含文件名,命令為hdfs.put(localfile, remotefile)。
3.4 hdfs操作封裝
同樣將我封裝的hdfs操作代碼封裝如下:
def mkdir(remotepath): if not exists(remotepath): hdfs.mkdir(dir) def get(remotepath, localpath): if exists(remotepath): hdfs.get(remotepath, localpath) def put(localfile, remotefile): dir = getDirPath(remotefile) mkdir(dir) hdfs.put(localfile, remotefile) def exists(remotepath): return hdfs.exists(remotepath) def delete(remotepath): if exists(remotepath): hdfs.rm(remotepath, recursive=True)
四、總結
本文簡單總結了python的部分常用基礎操作以及hdfs操作,最后還要說明一點,對這種非強類型的語言,在定義變量名稱以及傳入參數的時候一定要小心,否則會出現一些莫名其妙的錯誤。