简体   繁体   English

不能在 python 中使用打开的 function

[英]Cant use open function in python

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即使我的电脑中有文件

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. Go 到包含该文件的目录,然后尝试运行该文件。

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"所需文件路径:“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.这应该可以让您深入了解您遇到问题的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM