python 合并文件的具体实例

yipeiwu_com5年前Python基础
支持两种用法:
(1)合并某一文件夹下的所有文件(忽略文件夹等非文件条目)
(2)显示的合并多文件。
复制代码 代码如下:

import sys
import os
'''
    usage(1): merge_files pathname
              pathname is directory and merge files in pathname directory
    usage(2): merge_files file1 file2 [file3[...]]
'''
FILE_SLIM = (256*(1024*1024)) #256M match 2**n
def merge_files(fileslist,mfname):
    global FILE_SLIM
    p_fp = open(mfname,"wba")
    for file in fileslist:
        with open(file,"rb") as c_fp:
            fsize = os.stat(file).st_size
            count = fsize&FILE_SLIM
            while count>0:
                p_fp.write(c_fp.read(FILE_SLIM))
                fsize -= FILE_SLIM
                count -= 1
            p_fp.write(c_fp.read())
    p_fp.close
def main():
    argc = len(sys.argv) - 1
    fileslist = []
    if argc == 2:
        dir_name = os.path.realpath(sys.argv[1])
        assert(os.path.isdir(dir_name))
        file_dir = os.listdir(dir_name)
        fileslist = [os.path.join(dir_name,file) for file in file_dir if os.path.isfile(os.path.join(dir_name,file))]
        print(fileslist)
    elif argc >=3:
        fileslist = [os.path.realpath(sys.argv[index]) for index in range(1,argc) if os.path.isfile(os.path.realpath(sys.argv[index]))]
    merge_files(fileslist,sys.argv[argc])
if __name__ == '__main__':
    main()

相关文章

python中字典(Dictionary)用法实例详解

本文实例讲述了python中字典(Dictionary)用法。分享给大家供大家参考。具体分析如下: 字典(Dictionary)是一种映射结构的数据类型,由无序的“键-值对”组成。字典的...

Python模块future用法原理详解

这篇文章主要介绍了Python模块future用法原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 计算机的知识太多了,很多东西...

基于Django URL传参 FORM表单传数据 get post的用法实例

POST和GET是web开发中常用的表单交互方法,是构建web前后端交互系统的顶梁柱,现将Django中的简单用法示例记录下来,以供后续查询和其他同学参考 1.URL传参 #前端ht...

Python使用matplotlib绘图无法显示中文问题的解决方法

Python使用matplotlib绘图无法显示中文问题的解决方法

本文实例讲述了Python使用matplotlib绘图无法显示中文问题的解决方法。分享给大家供大家参考,具体如下: 在python中,默认情况下是无法显示中文的,如下代码: impo...

详解Python循环作用域与闭包

前言 首先来看一段代码 x_list = [i for i in range(30)] y_list = [i for i in range(10, 20)] for y in y...