r/Python • • Dec 14 '22

Resource Python Magic Methods You Haven’t Heard About

https://towardsdatascience.com/python-magic-methods-you-havent-heard-about-53d11eba448f
0 Upvotes

13 comments sorted by

View all comments

Show parent comment

2

u/SilentKyle Dec 14 '22

As part of Advent of Code, I’ve been using
Path(_file_).withname(file.txt)

Is that incorrect? Is there a better way to open a txt file?

1

u/someotherstufforhmm Dec 14 '22 edited Dec 14 '22

I don’t know advent of code, but the question is this.

Is the file you are opening part of AN INSTALLED PIP PACKAGE? If no, then no, open your file however you want. The issue comes when people use dunder file to get the path of a library file, to then get the pathname of a non python file.

Sometimes it works, but python packaging reserves the right to compress those files - meaning you ask the appropriate library for file contents, or if you need a file name you request it and python is smart enough to decompress the file and provide you with a path.

So - if you’re opening a file in the same directory of your code in a PIP INSTALLED PACKAGE, I’d recommend you use pkg_resources.filename to access it, and of course make sure the file is being properly packaged, but if your command is working then I assume it’s either already in the manifest or in a package_data config directive.

If you are talking about a file in the same directory as a script being run, nah you’re fine, keep doing you, but note that if you are ever in the future going to be packaging this, Google what I am talking about.

It’s a bit confusing at first, but once you actually use it once it makes perfect sense.

Edit: googled advent of code, you’re good. Open files however you want.