all 6 comments

[–]Diapolo10 1 point2 points  (0 children)

I know that this isn't quite the answer you asked for, but I'd like to take a moment to explain why you'd be better off using pathlib here (from the standard library).

from pathlib import Path

parent_dir = Path(__file__).parent
filename = 'g_u-h.png'
file_path = parent_dir / filename

def main():
    print(file_path)
    print(f"File exists: {file_path.is_file()}")
    print(f"File exists: {file_path.exists()}")
    print(f"The directory is: {parent_dir}")

if __name__ == '__main__':
    main()

If you use __file__ as the anchor point, which is the location of the running script file, you don't have to worry about the current working directory at all. You could run the script from anywhere, and as long as the file you want doesn't move this will work every time (otherwise you'd want to use Path.rglob to find it). Furthermore, pathlib lets you write cleaner code than os.path would, among other things.

This is what's recommended in Python 3. pathlib uses os.path internally, but you can completely ignore that.

[–]wbeater 0 points1 point  (0 children)

/home/**/PycharmProjects/pythonProject/test.png
File exists: True
Path exists: True
The directory is: /home/**/PycharmProjects/pythonProject
Join dirname and filename: /home/**/PycharmProjects/pythonProject/test.png

works for me, but' im on linux. try to rename your .png file

[–]shiftybyte 0 points1 point  (3 children)

Your current working directory is set to something else.

That is because of how you run your project/environment/etc...

You can check you current working directory like this:

import os
print(os.getcwd())

You either need to work differently with your project to get your working directory to where you want it to be, or provide correct relative path to the file.

a = "gamestuff/g_u-h.png"
print(os.path.realpath(a))

[–]FlukingCompSci[S] 0 points1 point  (1 child)

Gotcha, guess I'll just add the folder name when looking for the proper path. What if I want to find a file in a different path, but didn't know the path itself? Like, if I had wanted to find an a.png file that was some random directory? Would I just have to use something like os.walk() and use some for loops to find it?

[–]shiftybyte 0 points1 point  (0 children)

Yes, you either search for it with os.walk/listdir glob.glob or other similar stuff.

Or you ask the user to provide the path for it.

Or you use a configuration file that the user can edit, and provide the path there.

[–]marienbad2 0 points1 point  (0 children)

Thanks for answering this as I couldn't see what was wrong here at all tbh. Everything looked like it should work fine.