We know that when you put a resource file together with a .py file, you can read it directly in that .py file, using the filename. For example:
with open('') as f: content = () print('The contents of the file are:', content)
The running effect is shown below:
But please note that here I am running the file directly. What if the resource file is stored in a package, and we call the .py file inside that package from the outside? Let's give it a try:
As you can see, Python can't find the file now. This is because our entry program is in the ~/get_title folder and the file is in the ~/get_title/util folder. Because we're running it, Python looks inside the ~/get_title folder and naturally can't find it.
If you are referencing other modules in the package, you can use relative paths. For example, if you are referencing a conn object inside a package called sql_util.py, you can write from .sql_util import conn, but you can't use a relative path to read a resource file, as shown in the following figure:
One dumb way to do this is to get the folder where this line of code is currently running, and then spell out the full path to the resource file. Modify the file:
import os def read_file(): current_folder = (__file__) resource_path = (current_folder, '') with open(resource_path) as f: content = () print('The contents of the file are:', content)
The running effect is shown below:
But it's slightly more cumbersome to write it that way.
If your version of Python is not lower than 3.7, then you can use to read resource files quickly:
from importlib import resources with resources.open_text('Package name', 'Resource Path') as f: content = ()
The running effect is shown below:
If you are reading something other than a text file, then you can read a binary file by changing resources.open_text to resources.open_binary.
However, it is important to note that the resource file must be placed in the root directory of the package. This way it can be read correctly. If the resource file is in a subdirectory inside the package, it cannot be read directly.
For example, our package is util, there is a folder called deep_folder, the resource file is placed in deep_folder, at this time, if we want to read this resource file, we have to put in the deep_folder folder to create one, turn it into a package as well. Then the modified code:
from importlib import resources from . import deep_folder def read_file(): with resources.open_text(deep_folder, '') as f: content = () print('The contents of the file are:', content)
Import deep_folder as a module, and then use this module as the first parameter of resources.open_text. This way it can be read correctly, as shown below:
This is the whole content of this article.