Path and base64 ¶
Delete files under a directory ¶
1 directory = Path("tmp/")
2 for entry in repertoire.rglob("stats_employe_*.csv"):
3 entry.unlink()
Building a zip file from csv files ¶
1 directory = Path("tmp/")
2 zipfilename_partiel = f"stats_employes_{selected_year}.zip"
3 zipfilename = f"tmp/{zipfilename_partiel}"
4 with zipfile.ZipFile(zipfilename, "w", zipfile.ZIP_DEFLATED) as zip_file:
5 for entry in directory.rglob("stats_employe_*.csv"):
6 zip_file.write(entry, entry.relative_to(dir))
decode base64 ¶
1"""Transforme une image codée en base64
2 en image au format PNG
3
4 .
5 ├── decode_base64.py
6 ├── images
7 │ ├── base_64_cca.png
8 │ ├── base_64_cca.txt
9 │ ├── base_64_galgadot.png
10 │ ├── base_64_galgadot.txt
11 │ ├── base_64_hemsworh_1.png
12 │ ├── base_64_hemsworh_1.txt
13 │ ├── base_64_hemsworh_2.png
14 │ ├── base_64_hemsworh_2.txt
15 │ ├── base_64_male_tpdne.png
16 │ ├── base_64_male_tpdne.txt
17 │ ├── base_64_rd.png
18 │ └── base_64_rd.txt
19 ├── poetry.lock
20 └── pyproject.toml
21
22
23"""
24import base64
25import sys
26from io import BytesIO
27from pathlib import Path
28
29from PIL import Image
30
31
32def decode_and_save_image(base64_filename: Path):
33 """
34
35 >>> base64_filename
36 PosixPath('images/base_64_cca.txt')
37
38 >>> base64_filename.stem
39 'base_64_cca'
40
41 >>> output_image = base64_filename.parent / (base64_filename.stem + ".png")
42 >>> output_image
43 PosixPath('images/base_64_cca.png')
44
45 """
46 output_image_filename = base64_filename.parent / (
47 base64_filename.stem.removeprefix("base_64_") + ".png"
48 )
49 print(f"{base64_filename=}\n{output_image_filename=}")
50 f = open(base64_filename, "r")
51 data = f.read()
52 f.close()
53 im = Image.open(BytesIO(base64.b64decode(data)))
54 im.save(output_image_filename, "PNG")
55
56
57if __name__ == "__main__":
58 """Point d'entrée du script Python."""
59 base64_filename = Path(".")
60 for i, argument in enumerate(sys.argv):
61 if argument == "--file":
62 base64_filename = Path(sys.argv[i + 1])
63
64 decode_and_save_image(base64_filename)