Python对文件系统的几个操作

2018-11-17  本文已影响0人  门朝大海

刚做了一个小需求,对文件系统有一些操作,记录一下,巩固记忆。

获取文件自己所在的路径:

 pwd = os.getcwd()

创建文件夹:

def create_dir(dirpath):
    # 判断目录是否存在,不存在则创建
    if not os.path.exists("{path}/localfiles".format(path=dirpath)):
        os.makedirs("{path}/localfiles".format(path=dirpath))

删除文件:

def remove_files():
    # 判断本地日志文件夹是否为空,如果不为空,就删除目录下所有文件. 
    if os.listdir(local_path):
        os.popen("""rm {local_path}*""".format(local_path=local_path))

    # 判断加载文件是否存在,存在就删除
    if os.path.exists(load_path):
        os.remove(load_path)

下载hdfs 文件本地:

def getFileFromHdfs(hdfs_dir,hdfs_path):
    # 判断openapi 日志hdfs上是否存在。
    output = os.popen("""hdfs dfs -test -e {hdfs_dir} \n echo $? """.format(hdfs_dir = hdfs_dir))
    r = output.readline()

    # readlines() 的结果最后面总是带着一个 \n
    r = r.split('\n')[0]

    # 如果日志路径不存在 pass
    if r == '1':
        pass
    else:
        os.popen("""hdfs dfs -get {hdfs_path} {local_path}""".format(hdfs_path = hdfs_path,local_path = local_path))

读取本地日志文件,去掉 _SUCCESS 文件:

def read_logs():
    # 读取文件夹中文件列表
    try:
        files = os.listdir(local_path)
    except Exception as e:
        print('读取文件列表报错:'+ traceback.format_exc())
    
    #如果为0,那就说明目录下并没有文件。
    if len(files) != 0:
        # 遍历这些个文件
        for file in files:
            # 去掉文件夹
            if not os.path.isdir(file):
                # 去掉 _SUCCESS 文件
                fname = os.path.basename(file)
                if fname == '_SUCCESS':
                    pass
                else:
                    # 解析日志文件并写入本地文件
                    analysis_logs(fname)

按行读取文件并去掉空行

        with open(file_path,'r') as f:
            for line in f.readlines():
                # 判断是否为空行。可能是\n,也可能是空格
                if line in ['\n','\r\n'] or line.strip() == "":
                    pass
上一篇下一篇

猜你喜欢

热点阅读