Skip to content

Commit

Permalink
2 new tips
Browse files Browse the repository at this point in the history
  • Loading branch information
bbelderbos committed Jul 11, 2024
1 parent 329268d commit b4e1274
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
5 changes: 5 additions & 0 deletions index.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ This file gets generated by [this script](index.py).

- [Itertools.count](notes/20220906094357.md)
- [Pathlib list files in directory](notes/20220904164101.md)
- [Slicing generators](notes/20240711112100.md)
- [Split a sequence into pairs](notes/20231216210001.md)

## Git
Expand Down Expand Up @@ -332,6 +333,10 @@ This file gets generated by [this script](index.py).
- [Pathlib list files in directory](notes/20220904164101.md)
- [Read / write files the modern way](notes/20221202131250.md)

## Pdf

- [Merge pdf files](notes/20240711112142.md)

## Performance

- [More performant string building](notes/20231218133029.md)
Expand Down
35 changes: 35 additions & 0 deletions notes/20240711112100.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# slicing generators

Ever wondered how to slice a #Python generator?

You can use `itertools.islice()`:

```
>>> def gen():
... yield from range(1, 11)
...
>>> g = gen()
>>> g[:2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable
>>> from itertools import islice
>>> my_slice = islice(g, 2)
>>> my_slice
<itertools.islice object at 0x7fb2ab084540>
>>> list(my_slice)
[1, 2]
>>> [i for i in g]
[3, 4, 5, 6, 7, 8, 9, 10]
# another example of generator exhaustion:
>>> g = gen()
>>> ', '.join(str(i) for i in g)
'1, 2, 3, 4, 5, 6, 7, 8, 9, 10'
>>> ', '.join(str(i) for i in g)
''
```

#generators
21 changes: 21 additions & 0 deletions notes/20240711112142.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# merge PDF files

TIL how to merge PDF files in Python -> the `pypdf` library makes this really easy:

```
from itertools import islice
from pathlib import Path
from pypdf import PdfWriter
with PdfWriter() as merger:
files = (Path.home() / "code" / "articles" / "outputs").glob('*.pdf')
for file in islice(files, 3):
merger.append(file)
merger.write("output.pdf")
```

Source project where I found this: https://github.com/ahmedlemine/pdf-merger

#pdf

0 comments on commit b4e1274

Please sign in to comment.