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__))
Related
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.
I am getting this error sometimes when working on mac in Processing for Python. Seemingly for no reason, sometimes the current working directory becomes what you see in the image while other times it is the working directory of the folder the pyde file is in as it should be.
Any ideas on why this is occurring?
It's to avoid problems like these that I always try to use absolute paths. I would suggest you try something like this for file paths:
import os
# This will be the path to your .py file
FILE_PATH = os.path.dirname(os.path.abspath(__file__))
# This will be the path to your text file, if it is in the same directory as the .py
LEVELS_FILE_PATH = os.path.join(FILE_PATH, "levels.txt")
Then, instead of your current open statement you could have:
f = open(LEVELS_FILE_PATH, 'r')
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
I think that's easy but my script doesn't work. I think it's gonna be easier if I show you what I want: I want a script (in python) which does that:
I have a directory like:
boite_noire/
....helloworld/
....test1.txt/
....test2.txt/
And after running the script I would like something like:
boite_noire/
helloworld/
....test1/
........test1_date.txt
....test2/
........test2_date.txt
and if I add an other test1.txt like:
boite_noire/
helloworld/
....test1/
........test1_date.txt
....test2/
........test2_date.txt
....test1.txt
The next time I run the script:
boite_noire/
helloworld/
....test1/
........test1_date.txt
........test1_date.txt
....test2/
........test2_date.txt
I wrote this script :
But os.walk read files in directories and then create a directory named as the file, and I don't want that :(
Can someone help me please?
You could loop through each file and move it into the correct directory. This will work on a linux system (not sure about Windows - maybe better to use the shutil.move command).
import os
import time
d = 'www/boite_noire'
date = time.strftime('%Y_%m_%d_%H_%M_%S')
filesAll = os.listdir(d)
filesValid= [i for i in filesAll if i[-4:]=='.txt']
for f in filesValid:
newName = f[:-4]+'_'+date+'.txt'
try:
os.mkdir('{0}/{1}'.format(d, f[:-4]))
except:
print 'Directory {0}/{1} already exists'.format(d, f[:-4])
os.system('mv {0}/{1} {0}/{2}/{3}'.format(d, f, f[:-4], newName))
This is what the code is doing:
Find all file in a specified directory
Check the extension is .txt
For each valid file:
Create a new name by appending the date/time
Create the directory if it exists
move the file into the directory (changing the name as it is moved)
I'm new to Python and really want this command to work so I have been looking around on google but I still can't find any solution. I'm trying to make a script that deletes a folder inside the folder my Blender game are inside so i have been trying out those commands:
import shutil
from bge import logic
path = bge.logic.expandPath("//")
shutil.rmtree.path+("/killme") # remove dir and all contains
The Folder i want to delete is called "killme" and I know you can just do: shutil.rmtree(Path)
but I want the path to start at the folder that the game is in and not the full C:/programs/blabla/blabla/test/killme path.
Happy if someone could explain.
I think you are using shutil.rmtree command in wrong way. You may use the following.
shutil.rmtree(path+"/killme")
Look at the reference https://docs.python.org/3/library/shutil.html#shutil.rmtree
Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)
Assuming that your current project directory is 'test'. Then, your code will look like the follwing:
import shutil
from bge import logic
path = os.getcwd() # C:/programs/blabla/blabla/test/
shutil.rmtree(path+"/killme") # remove dir and all contains
NOTE: It will fail if the files are read only in the folder.
Hope it helps!
What you could do is set a base path like
basePath = "/bla_bla/"
and then append the path and use something like:
shutil.rmtree(basePath+yourGamePath)
If you are executing the python as a standalone script that is inside the desired folder, you can do the following:
#!/usr/bin/env_python
import os
cwd = os.getcwd()
shutil.rmtree(cwd)
Hope my answer was helpful
The best thing you could do is use the os library.
Then with the os.path function you can list all the directories and filenames and hence can delete/modify the required folders while extractring the name of folders in the same way you want.
for root, dirnames, files in os.walk("issues"):
for name in dirnames:
for filename in files:
*what you want*