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.
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 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")
I have created a Python program which works great on windows, but now I have brought it over to my Apple Mac to test it out. The application has a sqlite database and I also have a couple of error logging files which are being kept in when the application is installed or simply initialised from the source code.
On the windows platform, to define the the database path I used the following command:
appDataPath = os.environ["APPDATA"] + "\\FOLDERNAME\\"
But on my mac, I am getting the following stack trace:
Traceback (most recent call last):
File "main.py", line 9, in <module>
from view import tick
File "/Users/myname/Desktop/APPNAME/view/tick.py", line 8, in <module>
from controller import get
File "/Users/myname/Desktop/APPNAME/controller/get.py", line 4, in <module>
appDataPath = os.environ["/Users/myname/Desktop"] + "\\FOLDERNAME\\"
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: '/Users/myname/Desktop'
What can I do to make this work? I tried changing this to my desktop location but still no joy. Where does a mac store the applications data? On Windows as you may very well know, is in the Roaming directory.
Thanks in advance
os.environ is a dictionary containing environment variables. There is no variable called /Users/myname/Desktop. That's why you're getting a KeyError. But there is a variable called HOME.
>>> os.environ['HOME']
'/Users/NAME/'
That should work equally on windows and OSX.
Now, if you want to concatenate paths, you should use os.path.join:
>>> os.path.join(os.environ['HOME'], 'MYPROJECT')
'/Users/NAME/MYPROJECT'