How to reference another file (i.e. png or jpg) in another directory in Python3?

Question:

I’m using VS Code to program in Python. Instead of copying and pasting an image (or any other type of file) from one directory to the same directory my .py file is located in, I want to reference that image instead even if it’s in a different directory. Or, at least, make that directory’s path accessible from my program.

This is how my folders are structured.

- MainFolder
    - AssetsFolder
          - image.jpg
    - file.py

I tried:

import sys
sys.path.append('C:UsermynameMainFolderAssetsFolder')

But it didn’t seem to work.

Asked By: JhiThan

||

Answers:

In python, you need to use relative directories.
In this case, to access image.jpg from file.py, you will need to use the path, AssetsFolder/image.jpg.

In order to access a higher directory, use ../. For example, if the file locations were swapped (file.py inside of AssetsFolder and image.jpg inside of MainFolder), you would need to use the path, ../image.jpg.

Answered By: KingsMMA
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.