I want to check if a file exists before returning it. So inside my script, I did:
print("***********")
print(args.src_path)
print(os.path.isdir(args.src_path))
But the terminal returns that:
(val_env) jovyan#jupyter-me:~/use-cases/UC_Scene_understanding/Code_Woodscape/scripts$ python semantic_map_generator.py --src_path ../data/instance_annotations/ --dst_path ../data/semantic_annotations --semantic_class_mapping configs/semantic_mapping_9_classes.json --instance_class_mapping scripts/mappers/class_names.json
***********
../data/instance_annotations/
False
Traceback (most recent call last):
File "/home/jovyan/use-cases/UC_Scene_understanding/Code_Woodscape/scripts/semantic_map_generator.py", line 69, in <module>
src_path, dst_path, semantic_classes_mapping, instance_classes_mapping = parser_arguments()
File "/home/jovyan/use-cases/_Scene_understanding/Code_Woodscape/scripts/semantic_map_generator.py", line 63, in parser_arguments
raise Exception("Error: Check if the files or dirs in arguments exit!")
Exception: Error: Check if the files or dirs in arguments exit!
However, to me this ../data/instance_annotations/ is an example of dir that os.path.isdir(args.src_path) should return True.
Furthermore this directory exists:
$find
...
./scripts/semantic_map_generator.py
./scripts/polygon_generator.py
./scripts/mappers
./scripts/mappers/class_names.json
...
./scripts/box_2d_generator.py
./data
./data/semantic_annotations
./data/download.txt
Considering that this error is not related to this part and os.path.isdir() method returns if False the file or directory doesn't exist, this error is related to the later lines of this code (probably somewhere in this code you open and read a file) but
for checking existence of a file or directory I recommend you to try .exists() method instead of .isdir() method.
import os
os path.exists("blob/blob/blobfile.txt")
Reference: os.path.exists(path) [Python-doc]
Related
I'm doing something basic with python, and I'm getting a pretty common error, but not able to find exactly what's wrong. I'm trying to use a custom module (built by someone else). I have the folder structure like this:
There is the test folder, and I have a file testing.py within that:
The contents of testing.py is:
from util import get_data, plot_data
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
When I run this file, using python testing.py, I get this:
I went through the other questions that speak about paths, and this looks fine, so not sure what I am missing here. My environment is setup using conda, and the environment is active.
EDIT
As per #allan-wind, I made the relative edit, which got me past the error, but now getting different errors:
I tried the relative import, and it got past that error, but then it is now throwing this error:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 190, in get_context
ctx = _concrete_contexts[method]
KeyError: 'fork'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "grade_analysis.py", line 21, in <module>
from grading.grading import (
File "E:\_Repo\GT\CS7646\mls4tsp23\grading\grading.py", line 15, in <module>
multiprocessing.set_start_method('fork')
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 246, in set_start_method
self._actual_context = self.get_context(method)
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 238, in get_context
return super().get_context(method)
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 192, in get_context
raise ValueError('cannot find context for %r' % method)
ValueError: cannot find context for 'fork'
`
There are a number of ways to specify how to find modules:
Use a relative import:
from .util import get_data, plot_data
Set the environment variable PYTHONPATH includes the directory where you module resides.
See sys.meta_path
Just place utils in the same folder as your testing.py and the python interpreter you put that directory in your path. Other solutions would be to place utils in a directory that is already in your path, since if thats not the case, you cant import from "above" the current directory
I know there are questions like that but I still wanted to ask this because I couldn't solve, so there is my code:
#! python3
import os
my_path = 'E:\\Movies'
for folder in os.listdir(my_path):
size = os.path.getsize(folder)
print(f'size of the {folder} is: {size} ')
And I got this error:
Traceback (most recent call last):
File "c:/Users/ataba/OneDrive/Masaüstü/Programming/python/findingfiles.py", line 7, in <module>
size = os.path.getsize(folder)
File "C:\Program Files\Python37\lib\genericpath.py", line 50, in getsize
return os.stat(filename).st_size
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'FordvFerrari1080p'
When I write print(folder) instead of getting their size it shows the folders so I don't think the program can't find them.
The problem may be that you are passing as an argument to os.path.getsize() just the folder name instead of the whole path to the folder
It may be that you have the file name as 'FordvFerrari1080p' rather than 'FordvFerrari1080p.mp4' (or whatever file type it may be)
I am simply trying to open a .docx file, which is stored in the server shared area.
I have tried the following:
notesPath = '//SERVER/shared_data/FolderOne/notes.docx'
os.chdir('//SERVER/shared_data')
os.startfile(notesPath)
With the os.chdir I am changing the path for command prompt, as I believe thats the issue. Becasue when I call os.getcwd() it returns me C:\\Users\\Userone\\Desktop\\. Thats what I though it was good idea to use os.chdir, convert it to //server and go from there.
But when I change the os.chdir in my code, the chdir is set to:
'\\\\SERVER\\shared_data'
with too many slashes
How can I resolve this issue?
Traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Userone\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\Userone\Desktop\project\Main App.py", line 293, in noteopen
os.startfile(notesPath)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '//SERVER/shared_data/FolderOne/notes.docx'
Assuming it's a UNC path, just use a raw string and use back slashes. There should be no need to change the current directory.
notes_path = r'\\SERVER\shared_data\FolderOne\notes.docx'
os.startfile(notes_path)
file_path :- find your application or other file path. put as it is.
file_path = r'C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE'
os.startfile(file_paht)
copy of the application path and pest it.
Given the following code:
# Edit build number in test report
print(path) # TODO remove
html_report = fileinput.input(path, inplace=True)
for line in html_report:
print(line.replace('$BUILD_NUMBER',
args.number).rstrip())
html_report.close()
I get the following output:
/home/jenkins/workspace/reports/report201610261053.html
Traceback (most recent call last):
File "report_generator.py", line 58, in <module>
for line in html_report:
File "/usr/lib/python2.7/fileinput.py", line 252, in next
line = self.readline()
File "/usr/lib/python2.7/fileinput.py", line 321, in readline
os.rename(self._filename, self._backupfilename)
OSError: [Errno 2] No such file or directory
If I just use the command:
gedit /home/jenkins/workspace/reports/report201610261053.html
I can check that the file exists. In fact, if it didn't I would expect this error to be raised in the fileinput.input() line, not in the line loop.
Any idea of what's wrong?
What is your "path" value?
I think you should try to use absolute path
You can also check the user permissions to file.
I don't see anything wrong in the code that you have shown.
I can check that the file exists. In fact, if it didn't I would expect
this error to be raised in the fileinput.input() line, not in the line
loop.
The error is reported only when an attempt is made to open file and it happens in the for loop.
Is it possible that your code is running under a different user and doesn't see the file on that path as compared to you manually verifying file existence?
When I run my code from main, it runs perfectly fine, but when I try to build main into an exe using py2exe, it gives this error:
Traceback (most recent call last):
File "main.py", line 118, in <module>
menu.menu.Menu()
File "menu\menu.pyo", line 20, in __init__
File "settingsManager.pyo", line 61, in getSetting
File "settingsManager.pyo", line 148, in __init__
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\Users\\digiholic\\git\\universalSmashSystem\\main.exe\\settings\\rules/*.*'
The line it's referring to is:
for f in os.listdir(os.path.join(os.path.dirname(__file__),'settings','rules')):
It looks like os.listdir is using unix file pathing to find every file, and Windows is having none of that. Is there a way to use listdir in a way that won't blow up everything?
When you're running within the exe you need to check if the module is frozen, the path from __file__ is generally not what you expect when you're within an exe vs the raw python script. You need to access the location with something like this:
import imp, os, sys
def main_is_frozen():
return (hasattr(sys, "frozen") or # new py2exe
hasattr(sys, "importers") # old py2exe
or imp.is_frozen("__main__")) # tools/freeze
def get_main_dir():
if main_is_frozen():
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
Source: http://www.py2exe.org/index.cgi/HowToDetermineIfRunningFromExe
You can also check another direction here: http://www.py2exe.org/index.cgi/WhereAmI