Error generation when trying to create a directory using Python: [Winerror 2] The system cannot find the specified file

Asked

Viewed 54 times

-1

In a video class I watched, the teacher uses the following command to create a directory using Python:

import os

res = os.path.join(os.getcwd(), 'geek')
os.chdir(res)
print(os.getcwd())

Literally, that’s all it does. Since the directory 'geek' does not exist, this command creates it. However, when executing exactly the same code here, the following error is generated:

"Traceback (Most recent call last):

File "D: Program Files (x86) Jetbrains Pycharmprojects Guppe testes.py", line 4, in os.chdir(res)

Filenotfounderror: [Winerror 2] The system cannot find the specified file: ’D: Program Files (x86) Jetbrains Pycharmprojects Guppe geek'"

That is, on the computer in the teacher of the class, the command worked and created the directory "geek". Already here, this error is generated. I would like to know the reason for the error, since the code is exactly the same. Remember that in the video of the class is used Ubuntu, while I use Windows 10.

1 answer

-1


Your current code will successfully complete if the directory geek exists, but will fail if it does not exist. The command os.chdir does not create a directory if it does not exist. This is the function of the command os.mkdir:

import os

res = os.path.join(os.getcwd(), 'geek')
os.mkdir(res)
os.chdir(res)
print(os.getcwd())

The above code will successfully complete the directory geek does not exist, but will fail if it exists. To solve this problem, just use the function os.path.isdir:

import os

res = os.path.join(os.getcwd(), 'geek')

# Verifica se a pasta já existe; caso não, a cria
if not os.path.isdir(res):
    os.mkdir(res)

os.chdir(res)
print(os.getcwd())

The above code will successfully complete, be geek existing or not.

  • I get it. I just find it strange that in the case of video, the command that creates the directory is the res = os.path.join(os.getcwd(), 'geek'). The command os.chdir(res), from what I understand, it would only enter the directory after it was already created, and the os.mkdir(res) was not used in the video. However, the video lesson is from 2018, so I suppose that from then on they have changed this in Python, because precisely because it is video, you can see the command working "in real time". I believe before then it was possible.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.