How can I upload files so they work on other Pcs even if the path to the file is different? (Pygame)

Asked

Viewed 26 times

-2

Oops! So... I’m doing a program using the pygame, and when it comes time to upload a file, I should use this, right?

bulletImg = pygame.image.load('C:\Users\Tarcísio\PycharmProjects\pyGameSpI\imgs\bullet.png')

But this will only work on my computer, and not on other people’s computer, because the path to the file is different. What should I do?

  • 2

    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 library pathlib to manage this.

  • 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

1 answer

0

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.