The module os
, more specifically your method path
is the sollution for this type of case.
A huge advantage of using it is the abstraction of the separator between directories
import os
print(os.sep)
In the Linux and Osx systems the result would be: /
While on Windows: \
So you can build a directory like: f"primeiro{os.sep}segundo{os.sep}ultimo"
The result could be primeiro/segundo/ultimo
or primeiro\segundo\ultimo
Continuing. You can use the os.path.abspath
to take the absolute path of some relative path.
Example:
# o ponto passado como parâmetro corresponde ao diretório corrente
meu_diretorio = os.path.abspath(".")
On Linux and Osx, you’ll get something like /caminho/para/diretorio
while on Windows C:\caminho\para\diretorio
With this you could join a string to make a new directory, as below
meu_diretorio = os.path.abspath(".")
caminho_relativo = f"data{os.sep}arquivos"
arquivo = "nome_do_arquivo.ext"
full_path = os.path.join(meu_diretorio, caminho_relativo, arquivo)
print(full_path)
On Linux, the result would be something like:
/caminho/para/diretorio/data/arquivos/nome_do_arquivo.ext
Already on Windows:
C:\caminho\para\diretorio\data\arquivos\nome_do_arquivo.ext
Note: may be that the output on Windows is C:\\caminho\\para\\diretorio\\data\\arquivos\\nome_do_arquivo.ext
, on account of having to "escape" the \
More details on os.path
here
I believe the function
load
accepted, also, relative paths, so you do not need to enter the absolute path of the image. If you need the absolute, you can use the librarypathlib
to manage this.– Woss
Yes, I can put
'\imgs\bullet.png'
and the IDE (Pycharm) still recognizes, but when I try to run on CMD, only the absolute path works– Tarcísio Quintino