I'm trying to write a script where it will move a directory (containing images to be processed) into another dedicated working directory (within the project folder) by using shutil.move().
However, my Python script keeps on failing to achieve this by throwing an [Errno 2] No such file or directory: '/Users/user/Desktop/Captured\\ Images' exception.
The target directory is being perfectly recognised so that's not the issue.
I'm currently using macOS to develop this script, and using standard BASH.
This is how I input the path of the source directory (by dragging the folder into the terminal): /Users/user/Desktop/Captured\ Images.
This is how Python interprets the source directory: /Users/user/Desktop/Captured\\ Images.
The script works perfectly when I modify the source path to: /Users/user/Desktop/Captured Images.
I've also tried using the Pathlib Module to prevent file separator issues, but that also didn't work.
I know for sure that what's causing the problem is the \ within the file path since the folder is named 'Captured Images' with a space between it, thus Captured\ Images.
Here's the following source code:
move_directory(input("Please Input The Directory Of The Captured Images You Would Like To Import: "))
def move_directory(source_directory):
try:
shutil.move(source_directory, os.path.dirname(os.path.dirname(__file__)) + '/Captured Images/Source Images')
except OSError as errorMessage:
print("Failed To Move Directory: {0}".format(errorMessage))
Update 1:
I've just tried to move the directories by using subprocess.run(["mv", ...]) and it worked, so now I see that it's not how the script is taking in the input, but a problem between the path input and shutil.move().
Related
I have the following code to run a program located at
/Users/*/Downloads/Mood Script Static and another located a folder deeper at /Users/*/Downloads/Mood Script Static Edit/LowMood_Static. Now I am trying to invoke a subprocess controller that will run two python scripts, like this:
subprocess.call(['python3', 'SubjectSFbalance.py'])
print("\n")
time.sleep(0.5)
subprocess.call(['python3', 'LowMood_Static/LowMoodZScoring.py'])
However, when running the 2nd process, it correctly finds the .py script, but pandas cannot read the .csv files that are given in the LowMoodZScoring.py file, which is this:
Normalized_Subj = pd.read_csv('../SF_Output_Files/finished_sf_balance.csv')
giving the following error:
FileNotFoundError: [Errno 2] No such file or directory: '../SF_Output_Files/finished_sf_balance.csv'
However, when I run LowMoodZScoring.py without using the subprocess, I get no such error. What in subprocess is causing this error?
At first glance, since those CSV paths are relative, it looks like you need to add cwd="LowMood_Static" to the parameters of your subprocess call, so that it will run with that directory as the working directory.
To avoid this in a more comprehensive/future-proof way, it would be even better to have your LowMoodZScoring.py script load the CSV files relative to the directory of that script (i.e. os.path.dirname(__file__)), instead of relative to the current working directory.
data = pd.read_excel("ETH-USD")
I continually receive an error message informing me that the file cannot be found
this is despite the fact that
1: my directory has been changed within to Python to the same address as the folder where the excel file is stored
2: the file name is input exactly as displayed
Any ideas on why it is unable to find my file?
Is it possible that the excel file has an extension of .xlsx, but your file explorer is set to "hide file extensions"? Try:
data = pd.read_excel("ETH-USD.xlsx")
Or, see what's in the current directory by running:
import os
print(os.listdir())
A tip from the comments:
Windows tip too: hold Shift, right click the excel file and copy as path, then you can see its path (if you don't enable viewing file extensions in the file browser). –
creanion
Often when running python scripts from compilers the "working directory", or where you are running the script from doesn't match the location of your script, hence why I find it much more reliable to use this instead:
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
data = pd.read_excel(os.path.join(BASE_DIR,"ETH-USD")
To add, while I do not use Jupyter, in VSCode which I use, the working directory (which is where python looks for if you put a path in read_excel() but its not a full path) is often the current directory opened in there, so I expect a similar issue to be the reason for your issue.
[Introduction]
Hi! I'm working on a python script to automate installation of UWP-Apps, it's been a long time i'm not touching Python; until this day. The script uses Depedencies inside the script directory, i've looking up on my older scripts and found this specific code.
os.chdir(os.path.dirname(sys.argv[0]))
[Problematic]
However, using the above code doesn't work on my current script but it's working fine on older scripts. When using above, it shows:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''
Already looking up on Internet about this topic; but most of them was talking about running the script from outer/different directory that leads me to dead end.
Any helps is appreciated :)
The easiest answer is probably to change your working directory, then call the .py file from where it is:
cd path/to/python/file && python ../.py
Of course you might find it even easier to write a script that does it all for you, like so:
Save this as runPython.sh in the directory where you're running the python script from, is:
#!/bin/sh
cd path/to/python/file
python ../script.py
Make it executable (for yourself):
chmod +x ./runPython.sh
Then you can simply enter your directory and run it:
./runPython.sh
If you want to only make changes to the python script:
mydir = os.getcwd() # would be the folder where you're running the file
mydir_tmp = "path/to/python/file" # get the path
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd()
The reason you got an error was because sys.argv[0] is the name of the file itself, instead you can pass the directory as a string and use sys.argv[1] instead.
import os
from os.path import abspath, dirname
os.chdir(dirname(abspath(__file__)))
You can use dirname(abspath(__file__))) to get the parent directory of the python script and os.chdir into it to make the script run in the directory where it is located.
I'm having a strange issue. I'm just trying to do a basic show directory contents for relative path.
Created a test directory on the desktop
test directory contents
test.py
test1 -- folder
sample.txt
contents of test.py
import os
dataDir = "test1"
for file in os.listdir("/Users/username/Desktop/test"):
print(file)
Summary - absolute path
works - in visual studio code
works - macOS terminal python3 /Users/username/Desktop/test/test.py
however when use the variable I get an error:
contents of test.py
import os
dataDir = "test1"
for file in os.listdir(dataDir):
print(file)
Summary - relative path
works - in visual studio code
ERROR - macOS terminal python3 /Users/username/Desktop/test/test.py
Traceback (most recent call last):
File "/Users/username/Desktop/test/test.py", line 4, in
for file in os.listdir(dataDir):
FileNotFoundError: [Errno 2] No such file or directory: 'test1'
I all depends on what folder you are in when you launch the code.
Let's say your .py file is in folder1/folder2/file.py and your test1 folder is folder1/folder2/test1/.... You open a terminal in the folder1 and launch python3 /folder2/file.py. The program is going to check for files in folder1/test1/.
Try navigating to the actual file folder, that should work. If you want to use it wherever you launch the code you will have to do some checks on the current directory and manually point the code to the wanted path.
The following solution is inspired by that answer
A simple way to solve your problem is to create the absolute path. (I recommend using that always when you're working with different directories and files)
First of all, you need to care about your actual working directory. While using VS Code your working directory is in your desired directory (/Users/username/Desktop/test/).
But if you use the command line your actual working directory may change, depending where you're calling the script from.
To get the path where script is actually located, you can use the python variable __file__. __file__ is the full path to the directory where your script is located.
To use your script correctly and being able to call it using both ways, the following implementation can help you:
import os
dataDir = "test1"
# absolute path to the directory where your script is in
scriptDir = os.path.dirname(__file__)
# combining the path of your script and the 'searching' directory
absolutePath = os.path.join(scriptDir, dataDir)
for file in os.listdir(absolutePath):
print(file)
I have a little Python project of which I recently made a Conda package. Making the package was a pain on its own, however, I recently started adding tests to this using nosetests, which made it even harder.
To introduce: my package takes a certain input, performs a lot of (quantum chemical) calculations and then generates a folder in the same directory as the script which calls the package, containing the output data (some .png files, .txt files and binary files)
Using nosetests, I would like to check whether these output files are how they should be. I created a Python test script (using unittest) which creates the input and calls my package. Next, it imports the created file and the test file. However, this is where it goes wrong. I get the error that this file does not exist:
FileNotFoundError: [Errno 2] No such file or directory: 'results\\output.txt'
The directory looks like this:
project-path\
- tests\
- test-script.py
- results\
- output.txt
I call nose by running this in Anaconda prompt:
project-path> nosetests tests
And I import the file in the Python test script using:
result_file = open('results\\output.txt', 'r').read()
Does anyone know what goes wrong here? I think it has to do with the fact that the tests are executed in a test environment. In that case: how do I import my files?
Get the absolute path to output.txt, it is indeed the most reliable way to locate and open it.
import os, sys
basedir = os.path.dirname(sys.argv[0])
filename = "output.txt"
path = os.path.join(basedir, "results", filename)
result_file = open(path, 'r').read()