IOError in python: [Errno2] No such file or directory appears and gets stuck

Asked 2 years ago, Updated 2 years ago, 16 views

Python, or rather a beginner in programming.
I look forward to hearing from you.

Write the following code in a text editor (notepad) and then click
on your desktop. I saved it in my folder as mymod.py.

def countLines(name):
file=open(name)
return len(file.readlines())

Also, when I try to start using IDLE (Python GUI) using the following method,

>>import sys
>>sys.path.append("C:\Users\Owner\Desktop\c-file")
>>import mymod
>>mymod.test('mymod.py')

The following error occurred:

Traceback (most recent call last):
 File "<pyshell#3>", line 1, in <module>
  mymod.test('mymod.py')
 File "C:\Users\Owner\Desktop\c-file\mymod.py", line 9, intest
  return countLines(name), countChars(name)
 File "C:\Users\Owner\Desktop\c-file\mymod.py", line2, countLines
  file=open(name)

IOError: [Errno2] No such file or directory: 'mymod.py'

Could you tell me what this error means and how to deal with it?
By the way, I am using Python 2.7.11.
Thank you for your cooperation.

python

2022-09-30 15:31

2 Answers

We assume the following situations:

Python IDLE starts from a Windows Start menu (not on the command line)

->The current directory is probably the Python installation directory immediately after startup.You can check with the following code:

>>importos
>>print(os.getcwd())

mymod.py is stored in the directory "C:\Users\Owner\Desktop\c-file"

file=open(name) is interpreted as file=open('mymod.py').At this time,
Attempt to open the 'mymod.py' file in the current directory.

As a result of the above, there is no mymod.py file in the directory where Python was installed, so the error is No such file or directory.Workaround is one of the following:

A. Run os.chdir("C:\Users\Owner\Desktop\c-file") first.
B. Specify the file to open as the absolute path.


2022-09-30 15:31

No such file or directory: 'mymod.py'

mymod.py means "no file".
notepad saves by default with the extension .txt, so
Check to see if it's really saved in mymod.py or mymod.py.txt.(Depending on the status of the explorer, you may be in a mode where the extension is not displayed.)

Also, is the current directory a directory with files?
Try changing it to a full path.

Also,

def countLines(name):
    file=open(name)
    return len(file.readlines())

Indent as shown in
>>mymod.countLines('mymod.py')
I think you need to call it as shown in .


2022-09-30 15:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.