I am trying to use pkgutil.get_data to get resource from a package.
I have read through the documentation for this API , where it said
To use
pkgutil.get_data(package, resource).... Thepackageargument should be the name of a package, in standard module format (foo.bar). Theresourceargument should be in the form of a relative filename, using / as the path separator.
I am confused to understand the terminology standard module format (foo.bar). Let us say we have below example, and I want to get resource collection_effects.csv, how can I call this API ?
sound/ Top-level package
__init__.py Initialize the sound package
effects/ Subpackage for sound effects
__init__.py
echo.py
reverse.py
cool_effects/
collection_effects.csv
...
From documentation, I think I could call the resource by :
import pkgutil
res = pkg.util.get_data("sound.effects", "/cool_effects/collection_effects.csv")
,
however, it seems using below will also return a bytecode (From documentation, failed to get resource will return None):
res = pkg.util.get_data("sound/effects", "/cool_effects/collection_effects.csv")
I am confused on what standard module format means, and what is correct to call this API ?
I think this solves your problem
import pkgutil
res = pkgutil.get_data('sound.effects', 'cool_effects/collection_effects.csv')
And standard module format means what you use with import, so it requires __init__.py file. By e.g. you can add the __init__.py file to the cool_effects folder and then use this code, and it should works
import pkgutil
res = pkgutil.get_data('sound.effects.cool_effects', 'collection_effects.csv')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With