已知aThere are some in the foldertxt文件,如果bThere is also a file with the same name in the folder,把a中的文件拷貝到b,Finally put these copied files into onezip文件裡
代碼如下:
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)