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分析作业提交情况

python分析作业提交情况

这次做一个比较贴近我实际的东西:python分析作业提交情况。 要求:     将服务器中交作业的学生(根据文件的名字进行提取)和统计成绩的表格中...

python实现五子棋游戏(pygame版)

python实现五子棋游戏(pygame版)

本文实例为大家分享了python五子棋游戏的具体代码,供大家参考,具体内容如下 目录 简介 实现过程 结语 简介 使用python实现pygame版的五子棋游戏...

Python多进程池 multiprocessing Pool用法示例

本文实例讲述了Python多进程池 multiprocessing Pool用法。分享给大家供大家参考,具体如下: 1. 背景 由于需要写python程序, 定时、大量发送htttp请求...

Python获取邮件地址的方法

本文实例讲述了Python获取邮件地址的方法。分享给大家供大家参考。具体实现方法如下: import email.Utils   def getCleanMailAddress(st...

Python实现国外赌场热门游戏Craps(双骰子)

运行方法:     1. 打开python2 IDLE;     2. 输入 from craps import * &nb...