python 新建文件 hdfs_python基础操作以及hdfs操作
一、前言
作為一個全棧工程師,必須要熟練掌握各種語言。。。HelloWorld。最近就被“逼著”走向了python開發(fā)之路,大體實現(xiàn)的功能是寫一個通用類庫將服務(wù)器本地存儲的文件進行簡單清洗后轉(zhuǎn)儲到HDFS中,所以基本上python的相關(guān)知識都涉及到了,這里對一些基礎(chǔ)操作以及hdfs操作做一總結(jié),以備查閱。
二、基礎(chǔ)操作
2.1 字符串操作
字符串操作應(yīng)該是所有語言的基礎(chǔ)。python基本上也提供了其他語言常用的一些字符串處理函數(shù),常用的如下:
1、startswith 以某個字符串起始
2、endswith 以某個字符串結(jié)尾
3、contain python沒有提供contain函數(shù),可以使用 'test' in somestring 的方式來進行判斷,當(dāng)然也可以使用index來判斷
4、strip 去除空格及特殊符號
5、len 判斷字符串長度len(str)
6、upper lower 大小寫轉(zhuǎn)換
7、split 分隔字符串
2.2 文件操作
文件以及文件夾操作也是寫程序中經(jīng)常用到的功能。python中文件操作常用的有以下函數(shù)。
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 壓縮解壓縮操作
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有以下種,每種對應(yīng)不同的方式,需要根據(jù)自己需要選取:
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的選取,并且還要注意解壓縮的時候創(chuàng)建解壓縮文件時的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,必須保證其文件夾存在,否則會報錯,此時就可以先創(chuàng)建文件夾,只需要使用hdfs.mkdir(dir)即可,并且此命令會遞歸創(chuàng)建文件夾,即不需要一層層的創(chuàng)建不存在的文件夾。
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)
四、總結(jié)
本文簡單總結(jié)了python的部分常用基礎(chǔ)操作以及hdfs操作,最后還要說明一點,對這種非強類型的語言,在定義變量名稱以及傳入?yún)?shù)的時候一定要小心,否則會出現(xiàn)一些莫名其妙的錯誤。
新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎!定制產(chǎn)品紅包拿不停!總結(jié)
以上是生活随笔為你收集整理的python 新建文件 hdfs_python基础操作以及hdfs操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 功能强大!IntelliJ IDEA 2
- 下一篇: Java 8 八年不倒、IntelliJ