Home python FileNotFoundError: No such file or directory

FileNotFoundError: [Errno 2] No such file or directory




The command line gives an error FileNotFoundError: [Errno 2] No such file or directory , see the screenshot for details this)

I would appreciate your help.

Code script1.py:

import sys
print (sys.platform)
print (2 ** 100)
x = 'spam!'
print (x * 8)

Answer 1, authority 100%

There are various ways to set the path to a file or folder:

  • c: \ python370 \ script1.py – absolute path

  • script1.py – relative path, set relative to the current working directory. In this case, the file must be in the current directory.

In your case, the current directory is C: \ Users \ Acer , you are trying to open the file script1.py , but you have it not in this directory, but in c: \ python370 . Therefore, you will not open the file simply by the file name, you need to specify the full (absolute) path:

exec (open ('c: \\ python370 \\ script1.py'). read ())

Or start Python immediately from the desired directory – by double-clicking on the python.exe file in the c: \ python370 folder or in the cmd window first go to the directory where the required file is located, then start python, and try to open the file.

In a cmd window:

Microsoft Windows [Version 6.1.7601]
(c) Microsoft Corp. 2009. All rights reserved.
C: \ Users \ Michael & gt;

C: \ Users \ Michael is the current directory.

Change the current directory with this command (again in cmd, before starting python):

cd c: \ Python370

In python, you can find out the current directory by running the commands:

import os
print (os.getcwd ())

cwd is short for current working directory is the current working directory.

You can change the current directory from Python like this:

import os
os.chdir ('c: \\ python370')

As a result , if the current working directory does not match the directory where the file is located, then you cannot open the file simply by its name. You must either specify the full (absolute) path, or change the current directory.

By the way, in order not to escape backslashes in the path string, you can use “raw” strings, with the letter r in front of the quotes, for example:

import os
os.chdir (r'c: \ python370 ')

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions