python 合并文件的具体实例

yipeiwu_com6年前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对excel文档的操作方法详解

Python对excel文档的操作方法详解

本文实例讲述了Python对excel文档的操作方法。分享给大家供大家参考,具体如下: pip安装python库:(linux命令行输入不要在idle输入) pip install...

Python与Java间Socket通信实例代码

Python与Java间Socket通信   之前做过一款Java的通讯工具,有发消息发文件等基本功能.可大家也都知道Java写的界面无论是AWT或Swing,那简直不是人看的,对于我们...

利用Python如何生成随机密码

本位实例为大家分享了Python生成随机密码的实现过程,供大家参考,具体内容如下 写了个程序,主要是用来检测MySQL数据库的空密码和弱密码的, 在这里,定义了三类弱密码: 1. 连续数...

Python调用SQLPlus来操作和解析Oracle数据库的方法

先来看一个简单的利用python调用sqlplus来输出结果的例子: import os import sys from subprocess import Popen, PIPE...

使用python3批量下载rbsp数据的示例代码

使用python3批量下载rbsp数据的示例代码

1. 原始网站 https://www.rbsp-ect.lanl.gov/data_pub/rbspa/ 2. 算法说明 进入需要下载的数据所在的目录,获取并解析该目录下的信息,解析出...