This question already has an answer here:
Refering to a directory in a Flask app doesn't work unless the path is absolute
(1 answer)
Closed last year.
My application was working fine until yesterday - it's nearly finished and is due tonight. Yesterday for some reason it failed to recognise any of the files within the app folder (I am using VSC). I have no idea why this suddenly occurred, but I have checked the directory of the app.py file and it is the same path as my additional files. I even tried loading my project on a different pc incase the problem was with my internal file system, but got the same error.
The error printed below is for the first file my app calls, datab.yaml, but when I remove this I get the same error with the next file I try to call (sentiment_model.pkl), and so on.
Error:
File "c:\Users\jeram\Documents\NCI\Semester3\TriagatronX50\app.py", line 57, in <module>
db = yaml.safe_load(open('datab.yaml'))
FileNotFoundError: [Errno 2] No such file or directory: 'datab.yaml'
I have tried
import os.path
prog = ("/Users/jeram/Documents/NCI/Semester3/TriagatronX50")
directory = os.path.dirname(os.path.abspath(prog))
print(os.path.join(directory, 'datab.yaml'))
But it still throws the same error when I run it.
Any help very much appreciated!!
the problem is:
the directory of python file when executing is not the directory you put datab.yaml.
so, you should designate the whole abstract path of datab.yaml like the following:
import os.path
prog = ("/Users/jeram/Documents/NCI/Semester3/TriagatronX50")
directory = os.path.dirname(os.path.abspath(prog))
print(os.path.join(directory, 'datab.yaml'))
db = yaml.safe_load(open(os.path.join(directory, 'datab.yaml')))
and then execute it.
Related
To setup this question, I'm using Python in the form of Jython 2.7 (in Ignition SCADA). I have a function that copies image files to a print spool network folder. Occasionally I get an error like the following:
An ERROR occured: Line - 241: <type 'exceptions.IOError'>, [Errno 2] No such file or directory: u'\\server23\eFormz\D1234567.tif'. Part - ABC1234X12, while printing label.
These print jobs run through a number of different parts in the same order but only 1 or 2 generate this error. All others copy the file as expected. The error is calling out the DESTINATION file path in all cases. The destination folder exists as all of the good copies are going to the same folder as those that cause errors.
The code that does the copy looks like this:
import shutil
imgFiles = glob.glob(labelImage)
if len(imgFiles) > 0:
imgFile = imgFiles[0]
#ensure the image file path is actually a file
if os.path.isfile(imgFile):
fileName = imgFile.rsplit('\\', 1)[1]
dstFP = '\\\\server23\\eFormz\\' + fileName
shutil.copyfile(imgFile, dstFP)
Since this works most of the time, with the same folder paths and only the file name changing (all the source files are confirmed to exist and confirmed that they are indeed files, before attempting the copy), I'm perplexed as to the cause. File and folder permissions are the same for each so that should not be the cause.
Any ideas as to what may be causing this or a way to more effectively troubleshoot it would be appreciated.
Thanks.
This question already has answers here:
How to reliably open a file in the same directory as the currently running script
(9 answers)
Closed 2 years ago.
I am trying to open a file with python like this:
m = open("e.txt", 'r')
The text file I'm trying to open is in the same directory as my python file is.
However I'm getting an error message.
FileNotFoundError: [Errno 2] No such file or directory: 'e.txt'
I've also tried using:
import os
cwd = os.getcwd() # cwd: current working directory
path = os.path.join(cwd, "e.txt")
The error message looks a little different this time:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\user\\e.txt'
I hope someone can help me with this issue. Thanks in advance.
The could be in a folder, if this is the case then the full name has to be written. Such as:
m = open("E://folder/e.txt","r")
print(m.read())
It is important to write the EXACT directory of the file.
The code is perfectly correct. Check the type of file whether it is .txt or some other file. If everything is correct you should check the location you gave
I'm trying to use a program to read from a file with pi-digits. The program and the text file with the pi-digits are in the same directory, but i still get the error message :
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
Traceback (most recent call last):
File "C:\Python\Python_Work\python_crash_course\files_and_exceptions\file_reader.py", line 1, in <module>
with open('pi_digits.txt') as file_object:
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
I have looked for a solution but haven't found any.
I found a piece of code which supposedly shows me what the working directory is. I get an output that shows a directory that is 2 steps above the directory i have my programs and text file inside.
import os
cwd = os.getcwd() # Get the current working directory (cwd)
files = os.listdir(cwd) # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))
So when i put the pi text document in the directory that the output is showing (>python_work), the program is working. When it does not work is when the text file is in ">files_and_exceptions" which is the same file the program itself is inside. My directory looks like this when it is not working:
>python_work
>python_crash_course
>files_and_exceptions
file_reader.py
pi_digits.txt
show_working_directory.py
And like this when it is working:
>python_work
pi_digits.txt
>python_crash_course
>files_and_exceptions
file_reader.py
show_working_directory.py
I'm new to python and really appreciate any help.
Thanks!
Relative path (one not starting with a leading /) is relative to some directory. In this case (and generally*), it's relative to the current working directory of the process.
In your case, given the information you've provided, for it would be "python_crash_course/files_and_exceptions/pi_digits.txt" in the first case as you appear to be running the script from python_work directory.
If you know the file to be in the same directory as the script itself, you could also say:
import os.path
...
os.path.join(os.path.dirname(__file__), "pi_digits.txt")
instead of "pi_digits.txt". Or the same using pathlib:
from pathlib import Path
...
Path(__file__).with_name("pi_digits.txt")
Actually unless you have a point to anchor to like the script itself, using relative filename / path (using absolute paths brings its own problems too) in the code directly is rather fragile and in that case getting it as a parameter of a function (and ultimately argument of CLI or script call in general) or alternatively reading it from standard input would be more robust.
* I would not make that an absolute statement, because there are situations and functions that can explicitly provide different anchor point (e.g. os.path.relpath or openat(2); or as another example a symlink target)
I have a python script (db.py) which has a class(Chat) which refers to a json file(cred.json) saved in the same folder(db). This script runs perfectly fine without any error.
When I try to import the class Chat in a python script(wa.py) which is saved in one folder above folder db I get an error saying "[Errno 2] No such file or directory".
My folder structure looks like below
- wa.py
- db
- db.py
- cred.json
Piece of code in db.py where I am referring to the json file
cred_filename = 'creds.json'
with open(cred_filename, 'r') as c:
data = json.load(c)
wa.py looks like this
from db.db import Chat
I tried to find answer on google but couldn't find a relevant explanation for my case. I know there is something fundamentally wrong here but I am not able to figure it out.
Thanks in advance.
Essentially you're trying to open creds.json which is relative to your current working directory (unless changed during the runtime, one you have been in when calling the script) which does not need to be and apparently when this happens is not the one in which db.py resides.
This can only work and worked, as long as you were already in db/ when importing / running db.py.
If you always wanted to get creds.json in the directory where db.py resides, you could say for instance:
from pathlib import Path
...
cred_filename = Path(__file__).with_name("creds.json")
That takes path of the file this module is imported from and replaces the filename part with "creds.json".
I'm trying to rename the file names and extensions of all the files in a directory and move them to a new directory. I've read multiple post on how to do it but for some reason I haven't been successful and I've been stuck on this for 3 days now and feel like I'm doing something careless. Somebody get me on track please.
This is the latest way I've been trying.
import os
previousName = 'Macintosh HD/Users/kunductor/Desktop/folder3/windeffect.asd'
newName = 'Macintosh HD/Users/kunductor/Desktop/folder4/wind.wav'
os.rename(previousName,newName)
When I run the code above I get the message:
Traceback (most recent call last):
File "rename.py", line 7, in <module>
os.rename(previousName,newName)
FileNotFoundError: [Errno 2] No such file or directory
If it matters, I'm using macOS Mojave, version 10.14.2.
I tried replicating the same using Python 3 on Mojave 10.14.2. Use the paths starting from '/Users', and don't include Macintosh HD. The code runs perfectly when both folder3 and folder4 exist. I got a similar error when folder4 was removed, and the error message also specified the paths I passed as parameters.
If that's what you're experiencing, ensure that the directory you're trying to move the file to exists before calling os.rename. This can be done in Python itself by using the os.mkdir method. Since it throws an error if the directory already exists, you can check that by using the os.path.exists method.
this is the code that worked. I think the problem was that i was trying to change a non-audio file to a .wav and the system was rejecting it.
import os
# Function to rename multiple files
def main():
i = 0
for filename in os.listdir('/Users/vfloyd/Desktop/uu/'):
dst ="Kick" + str(i) + ".wav"
src = '/Users/vfloyd/Desktop/uu/'+ filename
dst ='/Users/vfloyd/Desktop/newD/'+ dst
# rename() function will
# rename all the files
os.rename(src, dst)
i += 1
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()