zoukankan      html  css  js  c++  java
  • python基础操作以及hdfs操作

    一、前言

           作为一个全栈工程师,必须要熟练掌握各种语言。。。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操作,最后还要说明一点,对这种非强类型的语言,在定义变量名称以及传入参数的时候一定要小心,否则会出现一些莫名其妙的错误。

  • 相关阅读:
    Python
    Python 学习之路
    Python 学习之路
    Python 学习之路
    Python 学习之路
    Python 学习之路
    Python 学习之路
    Python学习之路
    Python 学习之路
    Python 学习之路
  • 原文地址:https://www.cnblogs.com/hackerer/p/10823070.html
Copyright © 2011-2022 走看看