Python searching for image in wrong directory - python

I am trying to load some assets onto my program that I have them in a folder called 'Graphics', which is inside the folder 'Snake', which is inside the folder 'Projects', which is inside the folder 'Python'. However, also inside that folder 'Python' is another folder named 'HelloWorld'.
I am trying to load some assets in a program that I am running in 'Snake' and Python is searching for the assets in the 'HelloWorld' folder (which is where I used to keep my python files).
I get the error:
FileNotFoundError: No file 'Projects/Snake/Graphics/apple.png' found in working directory 'C:\Users\35192\OneDrive - WC\Desktop\Python\HelloWorld'
I believe that for this I have to change the default directory for vs code. I have changed the default directory for the command prompt and it did nothing. Perhaps this is because the python that I am running in the command prompt is different from the one in vs code (?)
How do I fix this?
Thank you in advance.
Edit:
This is how I am currently loading the image:
apple = pygame.image.load('Projects\Snake\Graphics\apple.png').convert_alpha()

Use pathlib to construct the path to your images. You wil have to add import pathlib to your code.
pathlib.Path(__file__) will give you the path to the current file. pathlib.Path(__file__).parent will give you the folder. Now you can construct the path with the / operator.
Try the following code and check the output.
import pathlib
print(pathlib.Path(__file__))
print(pathlib.Path(__file__).parent)
print(pathlib.Path(__file__).parent / 'Grahics' / 'apple.png')
Now you will be able to move the full project to a totally different folder without having to adjust any code.
Your code example looks like this: apple = pygame.image.load('Projects\Snake\Graphics\apple.png').convert_alpha()
If you import pathlib you can replace that with the dynamic approach:
path_to_image= pathlib.Path(__file__).parent / 'Grahics' / 'apple.png'
apple = pygame.image.load(path_to_image).convert_alpha()
I'm quite sure that pygame can work with a path from pathlib. If not then you have to convert the path to a string manually
apple = pygame.image.load(str(path_to_image)).convert_alpha()

You don't need to change the default directory. Just load from the full directory. That should look something like: "C:\Users\...\Python\Snake\Graphics\apple.png".

I think the simplest way is to first see your active directory by simply typing in
pwd, and then you could simply change the directory by cd("C:/path/to/location"), remember you have to use the backslash, or just use the following library:
import os
os.chdir("C:/path/to/location")
As pydragon posted, you could also import it by just giving the import function a path.

Related

Selenium how to save screenshot to specific directory in Python

I would like to take a screenshot for my selenium driver and save it to a specific directory. Right now, I can run:
driver.save_screenshot('1.png')
and it saves the screenshot within the same directory as my python script. However, I would like to save it within a subdirectory of my script.
I tried the following for each attempt, I have no idea where the screenshot was saved on my machine:
path = os.path.join(os.getcwd(), 'Screenshots', '1.png')
driver.save_screenshot(path)
driver.save_screenshot('./Screenshots/1.png')
driver.save_screenshot('Screenshots/1.png')
Here's a kinda hacky way, but it ought to work for your end result...
driver.save_screenshot('1.png')
os.system("mv 1.png /directory/you/want/")
You might need to use the absolute path for your file and/or directory in the command above, not 100% sure on that.
You can parse the file path you want to the save_screenshot function.
As your doing this already a good thing to check is that os.getcwd is the same as the location of the script (may be different if your calling it from somewhere else) and that the directory exists, this can be created via os.makedirs.
import os
from os import path
file_dir = path.join(os.getcwd(), "screenshots")
os.makedirs(file_dir, exist_ok=True)
file_path = path.join(file_dir, "screenshot_one.png")
driver.save_screenshot(file_path)
If os.getcwd is not the right location, the following will get the directory of the current script..
from os import path
file_dir = path.dirname(path.realpath(__file__))

Can i shorten a file location to the .py files location

first post here so sorry if it's hard to understand. Is it possible to shorten the directory in python to the location of the .py file?. For example, if I wanted to grab something from the directory "C:\Users\Person\Desktop\Code\Data\test.txt", and if the .py was located in the Code folder, could I shorten it to "\data\test.txt". I'm new to python so sorry if this is something really basic and I just didn't understand it correctly.
I forgot to add i plan to use this with multiple files, for example: "\data\test.txt" and \data\test2.txt
import os
CUR_FILE = os.path.abspath(__file__)
TARGET_FILE = "./data/test.txt"
print(os.path.join(CUR_FILE, TARGET_FILE))
With this, you can move around your Code directory anywhere and not have to worry about getting the full path to the file.
Also, you can run the script from anywhere and it will work (you don't have to move to Code's location to run the script.
You can import os and get current working directory ,this will give you the location of python file and then you can add the location of folder data and the file stored in that ,code is given below
import os
path=os.getcwd()
full_path1=path+"\data\test.txt"
full_path2=path+"\data\test2.txt"
print(full_path1)
print(full_path2)
I think this will work for your case and if it doesn't work then add a comment

Paraview PVpython running subscript from master script - relative path

I've got master script for PVPython which runs about 3-5 subscripts. Apart from aguments I always have to specify the subscript path in order to run it like this:
'/home/username/Documents/MainFolder/Subscripts/subscript1.py'
Is there a way to get this path automatically as the master script would be for example in same main folder like this:
'/home/username/Documents/MainFolder/Masters/master1.py'
When I run a relative path reference from PVPython like here I get an error, so maybe there's another way to do in PVPython?
Thanks for the tips
edit
The problem is that with
import sys
print(sys.path[0])
I get printed
/usr/lib/python38.zip
In the link you point to (https://note.nkmk.me/en/python-script-file-path/), there is a section Get the absolute path of the running file.
Use
os.path.abspath(__file__)
to get the absolute path of your master script. Then you can recreate the absolute paths of your subscripts from relative ones (see the os doc : https://docs.python.org/3/library/os.path.html)

python: cd into file

I have a script that creates a folder foo-12345. Issue is, the numbers in the folder change name anytime I run a per script that creates it. I'm trying to find a way to change directory into the folder so I can do a search. I tried using a variable:
import os
output = /var/foo-*
os.chdir(ouput)
This does not seem to work. Is there a way to capture that folder name in a variable and use that variable instead?
You can use the glob module to do it.
import glob
dirs = glob.glob('/var/foo-*')
The resulting dirs is a list, so you will need to process it as such. Have a look at the documentation

reading a file in python from different directory

Probably a simple query.. But basically, I have data in directory "/foo/bar/foobar.txt"
and I am working in directory "/some/path/read_foobar.py"..
Now I want to read the file "foobar.txt" but rather than giving full path, I thought of adding /foo/bar/ to the path..
So, added the following at the start of read_foobar.py
import sys
sys.path.append("/foo/bar")
But when I try to read open("foobar.txt","r"), it is not able to find the file?
how do I do this?
Thanks
You can do it like this:
import os
os.chdir('/foo/bar')
f = open('foobar.txt', 'r')
sys.path is used to set the path used to look for python modules. Short of you writing some helper function that has a list of directories to search in when opening a file, I don't believe there is a standard module that provides this functionality.
From what I gathered from here and some quick tests, appending a path to sys.path will make python search in that path when you import a file/module, but not when open-ing it. Let's say we have a file called foo.py in /foo/bar/
import sys
sys.path.append("/foo/bar/")
try:
f = open('foo.py', 'r')
except:
print('this did not work') # this will print
import foo # no problems here
Unfortunately you can't. The PATH environment variable is only used by the operating system to search for executable files, and python uses it (along with the environment variable PYTHONPATH) to search for python modules to import.
You may want to consider setting a symbolic link to that file from your current working directory
ln -s /foo/bar/foobar.txt /some/path/foobar.text

Categories

Resources