python 如何把多个文件内容合并到以一个文件

python 如何把多个文件内容合并到以一个文件,第1张

Python编程将多个文件合并,代码如下:

#例子:合并a.txt、b.txt、c.txt合并成逗喊d.txt文件

#文件列表,遍于读取

flist = ['a.txt','b.txt','c.txt']

#要写入的文件

ofile = open('d.txt', 'w')

#遍历读取所有文件,并写入到输出文件

for fr in flist:

    for txt in open(fr, 'r'):

        ofile.write(txt)

ofile.close()

效山仿野果如下大梁:

import os

s = os.sep #根据unix或win,s为\或/

root = "槐差d:" + s + "ll" + s #要遍历的目录

def func(args,dire,fis): #回调函数的定义

for f in fis:

fname = os.path.splitext(f) #分割文件名为名字和扩展名的二正铅元组

new = fname[0] + '铅清皮b' + fname[1] #改名字

os.rename(os.path.join(dire,f),os.path.join(dire,new)) #重命名

os.path.walk(root,func,()) #遍历

这个用不着python吧,

在windows下直接 Xcopy B A  /s /e /y

在linux下 cp -r A B

但是还是给你提供python的方法吧

#!/usr/bin/env python 

# -*- coding: utf-8 -*- 

"""

# ------------------------------------------------------------------------

# FileName:     [file_dir_copy.py]

# Purpose:      [copy dir B to A]

# ------------------------------------------------------------------------

"""

# import necessary module

import os

import shutil

from os.path import walk

oj = os.path.join

oif = os.path.isfile

oid = os.path.isdir

PathA = "D:\\PathA\\"

PathB = "D:\\PathB\\"

# ============================================================

def copy(arg, dirname, filenames):

    "碰汪""

    Purpose / Usage: copy() is a func to create dir and copy file

    from PathB to PathA by recursion

    Parameter(s):@arg, @dirname, @filenames

    """

    # for showing progress

    print dirname

    # remove root dir

    diretory = dirname.replace(PathB, "")

    dirnameA = os.path.join(PathA, diretory)

    if 败粗oid(dirnameA):

        # if there is a dir in PathA then check

        # if subdirs and files are existing.

        for FILE in filenames:

            if oif(oj(dirname, FILE)) and not oif(oj(dirnameA, FILE)):

                # if not exists files then copy files to pathA

                shutil.copy2(oj(dirname, FILE), oj(dirnameA, FILE))

            elif oid(oj(dirname, FILE)) and not oid(oj(dirnameA, FILE)):

                # if not exsits dir then make dir in PathA

                os.system("mkdir %s" % (oj(dirnameA, FILE)))

    else:

        # if there is no same dir, then create the dir in PatchA,

        # and copy files

        os.system("mkdir %s" % (dirnameA))

        察吵镇for FILE in filenames:

            shutil.copy2(oj(dirname, FILE), oj(dirnameA, FILE))

            # shutil.copy2 func can copy with original date

            # and time of file.

# ============================================================

if __name__ == "__main__":

    walk(PathB, copy, ())

    # call copy func recursively


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12146403.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存