Python拷贝txt文件,然后zip压缩它们

已知a文件夹里有一些txt文件,如果b文件夹里也有同名文件,把a中的文件拷贝到b,最后把这些拷贝的文件放进一个zip文件里

代码如下:

import time
from contextlib import contextmanager
from typing import List
from zipfile import ZipFile

import anyio  # pip install anyio
from anyio import Path


src_folder = Path("C:/Users/pushka/pythonApp1/src_folder")
dst_folder = Path("C:/Users/pushka/pythonApp1/dst_folder")


async def copy_file(from_path: Path, to_path: Path, copied) -> None:
    if await to_path.exists():
        content = await from_path.read_bytes()
        await to_path.write_bytes(content)
        copied.append(to_path)
        print(f"copy file: {from_path} --> {to_path}")


def zip_them(paths: List[Path]) -> str:
    filename = "copied.zip"
    with ZipFile(filename, "w") as z:
        for path in paths:
            z.write(path, path.name)
    return filename


async def main():
    copied = []
    async with anyio.create_task_group() as tg:
        async for p in src_folder.glob("*.txt"):
            dst = dst_folder / p.name
            tg.start_soon(copy_file, p, dst, copied)
    fn = zip_them(copied)
    print(f"zip file created: {fn}")


@contextmanager
def timeit():
    start = time.time()
    try:
        yield
    finally:
        end = time.time()
        print("Cost:", round(end - start, 2), "seconds.")


if __name__ == "__main__":
    with timeit():
        anyio.run(main)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值