python为什么会给我这个错误:filenotfound



我有一个不合理的错误,代码:

#====================================================#
#X Programming Language 2022(for Jadi) License: GPL  #
#====================================================#
from os import system #importing system func. for cmd
code_location = "" #saving code location in this
code = ""          #saving code in this
def main(): #main func.
code_location = input() #get code location from user
code = get_code() #cal get_code and save res to code var
print(code) #print code
end() #calling end
def get_code(): #get_code func. for getting code from file
code_file = open(code_location, 'r') #openning file with method read and saving to code_file
res = code_file.readlines() #saving the content from file to res
return res #returning res
def compiler(): #compiler func. for compiling code
pass
def end(): #when program end...
input("Press Enter to Countinue...")
if __name__ == "__main__":
main()

这是代码目录:在此处输入图像描述

正在运行:

在此处输入图像描述

简单回答:您的两个code_location变量不是一回事。

变量作用域

变量有一个称为scope的属性,它本质上是它们所属的上下文。除非另有指定,否则函数中的变量在该函数中仅存在。考虑:

a = 0
def set_a():
a = 1
set_a()
print(a)

这将打印0。这是因为函数set_a中的a变量实际上与第1行中定义的a是不同的变量。尽管它们有相同的名字,但它们指向记忆中不同的地方。

解决方案

有几种方法可以做到这一点:

定义范围

或者,您可以将函数中的作用域设置为global(而不是local(。现在,它所做的不是函数中指向不同内存位置的a,而是指向变量外与a相同的内存位置。这样做:

a = 0
def set_a():
global a
a = 1
set_a()
print(a)

在这种情况下,a将被设置为1;1〃;将打印

作为参数传递

另一种方法是将值作为变量传递给函数,这在您的环境中可能更相关。在您的情况下,您使用code_location作为文件路径,因此您希望将code_location传递到函数中。然后你必须这样定义你的函数:

def get_code(code_location):

并调用函数(从main函数(,如下所示:

code = get_code(code_location)

备注

对文件进行操作时,最好使用with块。这样可以在处理完文件后关闭文件,并且在代码出现问题的罕见情况下可以防止文件损坏。可以这样做:

with open(code_location, 'r') as code_file:
res = code_file.readlines()
return res
默认情况下,Python全局变量在本地作用域(例如函数的作用域(中是只读的。因此,在code_location = input()行中,您实际上是在创建一个新的同名局部变量,并将输入分配给它

为了写入全局变量,您首先必须声明您的意图:

def main(): #main func.
global code_location # DECLARE WRITE INTENTION FOR GLOBAL
code_location = input() #get code location from user
code = get_code() #cal get_code and save res to code var
print(code) #print code
end() #calling end

你不必在get_code()中做同样的事情,因为你只是在那里阅读code_location

PS:正如评论中所暗示的那样,在完成打开的文件后关闭它们是一种很好的做法:

def get_code(): #get_code func. for getting code from file
code_file = open(code_location, 'r') #openning file with method read and saving to code_file
res = code_file.readlines() #saving the content from file to res
code_file.close() # CLOSE FILE
return res #returning res

或者由上下文管理器自动完成:

def get_code(): #get_code func. for getting code from file
with open(code_location, 'r') as code_file: #openning file with method read and saving to code_file
res = code_file.readlines() #saving the content from file to res
return res #returning res

最新更新