0

I am using the PyCharm IDE. I marked a folder as a resource root and wanted to get a file from its directory and was wondering the appropriate way to do so.

In Java, you can use getClass().getResource("/resourceName.extension")

Is there some way to get a path from a python in said manner?

2 Answers 2

0

Based off what you have said it sounds like you just need to include the directory of the file with a simple include statement.

for instance, if your files are set up as such:

c:program\main
c:program\resources

then you can just do a simple

import resources

However, you could run into coupling issues if you have any sub-packages. Solving the coupling issue involving resources has been gone over in more detail in another thread I have linked below.

Managing resources in a Python project

Sign up to request clarification or add additional context in comments.

7 Comments

After importing the directory using import, how do you reference it when getting the file? For instance, I need to get an audio file called music.wav from resources. How would I go about getting it?
Is there a specific library you are using in your program? For instance, I generally make games using pygame and I set the sound doing sound = pygame.mixer.Sound("file") I did a little looking into how to do it outside of pygame. I found this document and hope it will help you out. docs.python.org/2/library/wave.html
I am using pyaudio. I am actually using wave to take in the file. I was just wondering if you could specify the package and file name or do some kind of relative path based on the resource root instead of using the absolute path or doing something like ../audio/music.wav.
With my programs, I tend to use a relative path for instance in one of my games my files are set up as game/Interface/file.py and game/Resources/Sounds and I just do self.sound = pygame.mixer.Sound("..\Resources\Sounds\Letters\Y.ogg") I haven't used pyaudio but I believe the same concept should apply. The documentation for pyaudio should have documentation on this.
I can use a relative directory as well in my case, but the point was to try to have a directory-independent way to get the file. Basically, I don't want it to be an absolute path so it will work on other people's computers no matter where the project is put. But I don't want it to be a simple relative path like ../audio/music.wav because, if the file is run from a different path in the directory, it will fail. For instance, if the file is executed from the project directory (e.g. python3 package/runner.py) instead of running it from the package directory (python3 runner.py), it would fail.
|
0

What I want can be accomplished by this answer.

I used the code as follows:

os.path.join(os.path.dirname(__file__), '../audio/music.wav'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.