so I have this problem in visual code, when I open a file in the same directory of a project, visual code doesn't identify the file unless I give him the whole directory
This is the image of the error:
cwd:
Specifies the current working directory for the debugger, which is the base folder for any relative paths used in code. If omitted, defaults to ${workspaceFolder} (the folder open in VS Code).
And you can set it to:${fileDirname} - the current opened file's dirname(official docs)
Try this way to set working directory manually:
/tmp/1/
/tmp/2/file
import os
print("Current working directory: {0}".format(os.getcwd()))
> Current working directory: /tmp/1
open('file', 'r')
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> FileNotFoundError: [Errno 2] No such file or directory: 'file'
os.chdir('/tmp/2')
open('file', 'r')
> <_io.TextIOWrapper name='file' mode='r' encoding='UTF-8'>
Also you can set directory related to the running python file:
import os
print(os.path.dirname(os.path.abspath(__file__)))
python /tmp/1/file.py
> /tmp/1
The good practice is to set application path somewhere in global configuration file
Related
I sporadically get this error using Python 3.10 in Windows. I've tried installing 3.7.8 to get around the error (based on prior posts) but it persists.
It can happen with any module, including os. For example, I can perform the command os.chdir() successfully but then when I try os.listdir() I get the error message.
This works:
file_loc = r"C:\Temp1\Registry\R2_XML_Files" # source directory for Registry
os.chdir(file_loc)
But then when I run
os.listdir(file_loc)
The error is
>>> os.listdir(file_loc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [WinError 87] The parameter is incorrect: 'C:\\Temp1\\Registry\\R2_XML_Files'
I've also tried using the pathlib module to troubleshoot Windows path issues with
file_loc = pathlib.PureWindowsPath ("C:/Temp1/Registry/R2_XML_Files")
but I still get the error
I've also tried not changing the directory but this code also fails:
file_loc = r"C:\Temp1\Registry\R2_XML_Files" # source directory for Registry
os.listdir(file_loc)
>>> os.listdir(file_loc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [WinError 87] The parameter is incorrect: 'C:\\Temp1\\Registry\\R2_XML_Files'
>>>
On a related note, I've also noticed when using the following code, I get a similar error, but only every 4 days. It runs for 3 days, then throws the same OSError. I can prevent the error by preemptively re-creating (in Windows) the folder "c:/Temp1/Covid"
dir_name = r"c:/Temp1/Covid"
extension = ".zip"
os.chdir(dir_name)
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(dir_name) # extract file to dir
zip_ref.close() # close file
os.remove(file_name)
Is there some Windows metadata that allows Windows to see and rename folders but does not allow Python to do so?
Have also run into the problem trying to pip install some modules.
I work for a hospital and have escalated to IT Security and no one seems to be able to figure out why this is occurring. The error also occurs for my colleagues and it is a huge hassle trying to keep Python stable. Starting over with a new install and new virtual environments sometimes works but sometimes doesn't.
Thanks very much.
I am attempting to make a simple pygame game, and I need to load in some images. When I run my code, or:
bg_image = pygame.image.load('assets/Fondotiff.tif(1).png').convert_alpha()
It gives me an error which says:
Traceback (most recent call last):
File "C:\Users\victo\Desktop\Assets - Pulga\mainpulga.py", line 12, in <module>
bg_image = pygame.image.load('assets/Fondotiff.tif(1).png').convert_alpha()
FileNotFoundError: No file 'assets/Fondotiff.tif(1).png' found in working directory 'C:\Users\victo\Desktop\Assets - Pulga'.
***Repl Closed***
I have double checked if the image is inside the folder on my desktop and it is there, but for some reason it doesn't find it.
How can I fix this?
The asset file path has to be relative to the current working directory. The working directory is possibly different from the directory of the python file.
It is not enough to put the files in the same directory or sub directory. You also need to set the working directory.
e.g.:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
I was trying to create a directory if it does not exists yet using the built-in pathlib from Python. My code looks like this:
Path("./src/CON").mkdir(parents=True, exist_ok=True)
However, I am running into this error:
Traceback (most recent call last):
File ".\main.py", line 16, in <module>
Path("./src/CON").mkdir(parents=True, exist_ok=True)
File "C:\Users\wangy80\AppData\Local\Programs\Python\Python38-32\lib\pathlib.py", line 1284, in mkdir
self._accessor.mkdir(self, mode)
NotADirectoryError: [WinError 267] The directory name is invalid: 'src\\CON'
The thing I don't understand is that if I replace CON with any other folder name it works perfectly (I am generating thousands of folders but only CON gives me an issue). There are no duplicated folders too. Why is this the case?
I'm on Windows10 running Python 3.8.5.
This was answered in the official Microsoft community:
You can't make folders on the desktop that have "System Action" or
"Device" references such as con, nul and prn. Solution is to use
another name or use 0 instead of o,O for C0n.
I have been instructed to change the working working directory. We were provided a file and instructed to put in the Documents folder if we were using a Mac. I cannot seem to to get it work.
from pathlib import Path
import os
Path.cwd()
print(os.getcwd())
os.chdir('/Users/VClark/Documents/cpt180Stuff')
Path.cwd()
print(os.getcwd())
This is the error I am getting:
/Users/VClark/Desktop/CPT 180
Traceback (most recent call last):
File "/Users/VClark/Desktop/CPT 180/workWithFiles.py", line 9, in <module>
os.chdir('Users/VClark/Documents/cpt180Stuff')
FileNotFoundError: [Errno 2] No such file or directory: 'Users/VClark/Documents/cpt180Stuff'
When you are dealing with directories, you must always have a "/" at the beginning of the file path, and at the end, indicating the last word is also a folder, or else it will be treated as a file. And you can't change directories to a file. /Users/hussein/Documents/ is good, Users/hussein/Documents/ and /Users/hussein/Documents are not.
When I used Windows, this was my code:
save_documents = open("pickled_algos/documents.pickle", "wb")
pickle.dump(documents, save_documents)
save_documents.close()
And what it did is make a second folder called "pickled_algos" and saved it there. Now I'm using Ubuntu Linux and when I write that same code I get this error:
Traceback (most recent call last):
File "PATH/sentimentProjectSaving.py", line 136, in <module>
save_documents = open("pickled_algos/documents.pickle", "wb")
FileNotFoundError: [Errno 2] No such file or directory: 'pickled_algos/documents.pickle'
How do I do the same thing I did in Windows, but on Linux?
EDIT: When I remove "pickled_algos/" then it works, the again the problem is that is saves into the same folder where the python file is.
One reason could be because you're using a relative path instead of an absolute path. Specifically, your error mentions that the directory can't be found so you should first check if the directory exists.
import os
path = 'your path'
# Create target Directory if doesn't exist
if not os.path.exists(path):
os.makedirs(path)
print("Directory created ")
else:
print("Directory already exists")