YSK: there is a library called pathlib with different methods for accessing files which you might like since they do not require a context manager
from SwordInStone@lemmy.world to python@programming.dev on 04 Dec 2024 16:53
https://lemmy.world/post/22766358

docs.python.org/3/library/pathlib.html

I’m creating this post mainly so that I don’t forget the name again.

#python

threaded - newest

joyjoy@lemm.ee on 04 Dec 2024 17:04 next collapse

os/os.path functions are named after their C counterparts.

Fred@programming.dev on 04 Dec 2024 17:06 next collapse

There was a discussion of pathlib a few days ago: programming.dev/post/21864360

SwordInStone@lemmy.world on 04 Dec 2024 20:27 collapse

sorry, I was looking for it today, which prompted me to create this post

eager_eagle@lemmy.world on 04 Dec 2024 17:21 next collapse

you can also enable this rule set to remind you docs.astral.sh/ruff/rules/#flake8-use-pathlib-pth

SwordInStone@lemmy.world on 04 Dec 2024 20:28 collapse

hell ye

FizzyOrange@programming.dev on 04 Dec 2024 18:03 next collapse

They still messed up the default encoding though unfortunately.

SwordInStone@lemmy.world on 04 Dec 2024 20:29 collapse

😢

troyunrau@lemmy.ca on 04 Dec 2024 18:07 next collapse

It’s also a really fun example of operator overloading. __div__ is overloaded to allow this syntax.

>>> p = PurePath('/etc')    
>>> p    
PurePosixPath('/etc')    
>>> p / 'init.d' / 'apache2'    
PurePosixPath('/etc/init.d/apache2')    
[deleted] on 05 Dec 2024 17:46 collapse
.
dallen@programming.dev on 05 Dec 2024 17:29 collapse

I subconsciously replace os.path with pathlib whenever touching any module for a refactor.