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')
Related
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__))
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'll try to be as simple as I can be. I'm not great at these things.
On my computer, at the location "C:\Users\Oria" there's a folder called Project. That folder contains code.ipynb, and a folder called data. Inside the folder data, there's just one file called iris_features.csv
I uploaded code.ipynb to jupyter notebook, there's a line there (which is locked to changes, can't change it) which reads
irisCsvFileName = 'data' + os.sep + 'iris_fearures.csv'
df_iris_features = pd.read_csv(irisCsvFileName)
So from what I understand, it should understand that the working directory is "C:\Users\Oria\Project" and all paths will be relative to it.
However, it doesn't work. It gives the error
FileNotFoundError: [Errno 2] File data\iris_fearures.csv does not exist: 'data\\iris_fearures.csv'
When I give the full path of the iris_features.csv, it works fine. However, as I said, I can't change the given code.
What am I doing wrong? Should I upload more than just the ipynb file to jupyter notebook?
There's a typo in the code you've provided in your question:
irisCsvFileName = 'data' + os.sep + 'iris_fearures.csv'
df_iris_features = pd.read_csv(irisCsvFileName)
You've written iris_fearures.csv but later have said that the file is called iris_features. You can check your current working directory is what you expect using:
import os
cwd = os.getcwd()
And you can find more information on using file paths etc in this SO answer
you have to give the full path if you didn't open the jupyter-notebook from the folder C:\Users\Oria\Project, if you just open a .ipynb from same folder Project the paths will not be relative to that .ipynb but with the folder from where you start the jupyter
you can check the current working directory (to whom all the other paths are relatives if they are not full paths):
import os
os.getcwd()
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 doing a Python course on Udacity. And there is a class called Rename Troubles, which presents the following incomplete code:
import os
def rename_files():
file_list = os.listdir("C:\Users\Nick\Desktop\temp")
print (file_list)
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "0123456789"))
rename_files()
As the instructor explains it, this will return an error because Python is not attempting to rename files in the right folder. He then proceeds to check the "current working directory", and then goes on to specify to Python which directory to rename files in.
This makes no sense to me. We are using the for loop to specifically tell Python that we want to rename the contents of file_list, which we have just pointed to the directory we need, in rename_files(). So why does it not attempt to rename in that folder? Why do we still need to figure out cwd and then change it?? The code looks entirely logical without any of that.
Look closely at what os.listdir() gives you. It returns only a list of names, not full paths.
You'll then proceed to os.rename one of those names, which will be interpreted as a relative path, relative to whatever your current working directory is.
Instead of messing with the current working directory, you can os.path.join() the path that you're searching to the front of both arguments to os.rename().
I think your code needs some formatting help.
The basic issue is that os.listdir() returns names relative to the directory specified (in this case an absolute path). But your script can be running from any directory. Manipulate the file names passed to os.rename() to account for this.
Look into relative and absolute paths, listdir returns names relative to the path (in this case absolute path) provided to listdir. os.rename is then given this relative name and unless the app's current working directory (usually the directory you launched the app from) is the same as provided to listdir this will fail.
There are a couple of alternative ways of handling this, changing the current working directory:
os.chdir("C:\Users\Nick\Desktop\temp")
for file_name in os.listdir(os.getcwd()):
os.rename(file_name, file_name.translate(None, "0123456789"))
Or use absolute paths:
directory = "C:\Users\Nick\Desktop\temp"
for file_name in os.listdir(directory):
old_file_path = os.path.join(directory, file_name)
new_file_path = os.path.join(directory, file_name.translate(None, "0123456789"))
os.rename(old_file_path, new_file_path)
You can get a file list from ANY existing directory - i.e.
os.listdir("C:\Users\Nick\Desktop\temp")
or
os.listdir("C:\Users\Nick\Desktop")
or
os.listdir("C:\Users\Nick")
etc.
The instance of the Python interpreter that you're using to run your code is being executed in a directory that is independent of any directory for which you're trying to get information. So, in order to rename the correct file, you need to specify the full path to that file (or the relative path from wherever you're running your Python interpreter).