Cant use open function in python

Viewed 13
try:
    with open("main.py") as file:
        print("File Opened")
    age = int(input("Enter your age- "))
    xfactor = age/10

except (ValueError, ZeroDivisionError):
    print("Invalid Age")

i get an error saying

Traceback (most recent call last):
  File "c:\Users\aksha\Desktop\python\main.py", line 2, in <module>
    with open("main.py") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'main.py'

even though i have the file in my pc

1 Answers

The problem you have encountered occurs because of a couple of reasons. One, the file does not exist in the same directory(folder) in which the terminal has been opened. The fix -

Go to the directory which contains the file and then try running the file.

Another reason could be that the path is not specified properly. This usually happens when the terminal is opened in the parent directory, but the file is inside some child directory.

Required file path: "child_directory_name/file_name"

A third reason could be that the file does not exist, and you are trying to create the file for the first time in which, your code can include a small tweak ...

try:
    with open("main.py", "w+") as file:
        print("File Opened")
    age = int(input("Enter your age- "))
    xfactor = age/10

except (ValueError, ZeroDivisionError):
    print("Invalid Age")

This should give some insight into why you are encountering the problem.

Related