(Apr-23-2024, 06:17 AM)Gribouillis Wrote: [ -> ]You could also write a generator and also you can have it produce Path instances if you want
import os
from pathlib import Path
def somefunc(root):
for d, _, files in os.walk(root):
p = Path(d)
for f in files:
yield p/f
To mix ios and pathlib may be more confusing than it need to be,this dos just the same with pathlib alone.
from pathlib import Path
def somefunc(root):
for path in Path(dest).rglob('*'):
if path.is_file():
yield path
In it's simplest form Winfried a strip down version of what DeaD_EyE code dos.
So this will recursively scan for all
.txt
in folder
Test
,all files would be
rglob('*')
.
from pathlib import Path
dest = r'C:\Test'
for path in Path(dest).rglob('*.txt'):
if path.is_file():
print(path)
Quote:I've never seen that syntax (def get_files(root: str | Path) -> Generator[Path, None, None]:) . I'll have to do some read up.
Look at
Support for type hints,so it can make code clearer what it take as input and expected output.
Can work as better documentation of code and also show this in Editors autocompletion when eg mouse over or use help what
get_files
dos.
It have no impact running it with Python,has to use eg
Mypy to do a static type check.
So as a example when i say not needed,this will work fine.
from pathlib import Path
def get_files(root):
"""
Generator, which recursively yields all files of a directory
"""
for path in Path(root).rglob("*.txt"):
if path.is_file():
yield path
dest = r'C:\Test'
for path in get_files(dest):
print(path)
So less code,but also lose information of what
root
can take as input eg it can take both
str
or
Path
as input.
Type hint is no used as standard in many biggest workplaces that use Python,also in many 3-party libraries.
Eg
FastAPI
Doc Wrote:FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints
.