Python出现FileNotFoundError求助:附代码及运行相关信息
为什么会触发FileNotFoundError?
你的问题出在变量作用域上:
- 你在全局定义了
code_location = "",但在main()函数里又重新赋值了code_location = input()——这会创建一个局部变量,和全局的code_location不是同一个。 - 当
get_code()函数执行open(code_location, 'r')时,它会去读取全局的code_location(也就是空字符串),而不是你输入的路径,自然找不到对应的文件。
修复方案有两种:
方案1:使用global声明变量
修改main()函数,明确指定使用全局的code_location:
def main(): #main func. global code_location # 声明使用全局变量 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
方案2:将路径作为参数传递(更推荐,避免全局变量污染)
修改get_code()函数,让它接收路径参数:
def main(): #main func. code_location = input() #get code location from user code = get_code(code_location) # 把输入的路径传进去 print(code) #print code end() #calling end def get_code(file_path): #get_code func. for getting code from file code_file = open(file_path, '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
另外,建议在打开文件时使用with语句,它会自动帮你关闭文件,避免资源泄漏:
def get_code(file_path): with open(file_path, 'r') as code_file: res = code_file.readlines() return res
内容的提问来源于stack exchange,提问作者arashDev
相关产品推荐
相关产品推荐

