<Python> 合并目录下指定的文件

使用BAT脚本为1-9.txt的文件添加0:
for /l %%a in (1 1 9) do ren %%a.txt 0%%a.txt

合并目录下00.txt~59.txt的文件:

import os
import re

def get_file_list(p):
    p = str(p)
    if p == "":
        return []

    p = p.replace("/", "\\")
    if p[-1] != "\\":
        p = p + "\\"

    listdir = os.listdir(p)
    sub_files = []
    for f in listdir:
        path = p + f
        if not os.path.isfile(path):
            continue
        if not re.match("([0-9]+)\\.txt", f):
            continue
        sub_files.append(path)

    return sub_files


# copy file contents for sure
def append_binaries(f_path):
    try:
        o_file = open(all_file, 'ab')
        in_file = open(f_path, "rb")
        contents = in_file.read()
        o_file.write(contents)
        o_file.close()
        return True
    except (FileExistsError, FileNotFoundError) as e:
        print(e)
        return False


all_file = "all.txt"
txt_files = get_file_list(".")
print(txt_files)
os.remove(all_file)
for f in txt_files:
    append_binaries(f)

print("Merge Completed!")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值