Python3.10读取txt文件赋值变量报Nx未定义NameError如何解决
问题排查与解决方案
错误根因
- 变量作用域限制:
ReadInput函数内部定义的Nx、Ny等变量属于函数局部变量,仅在函数执行周期内有效,函数外部无法直接访问 - 函数未调用:你从未执行过
ReadInput函数,即使没有作用域限制,相关变量也不会被初始化 - 隐含风险:代码直接用
open()打开文件后未主动关闭,可能引发文件资源泄漏
修复方案
改造ReadInput函数将读取到的所有参数返回,外部调用函数接收返回值后再执行后续计算,同时用with上下文管理器优化文件读取逻辑,自动处理文件关闭。
修复后的完整代码如下:
import os import numpy as np import matplotlib.pyplot as plot #import data into variables for use def ReadInput(diffsolverin): with open(diffsolverin,"r") as file: line = file.readline() # read the first line (remove comments from input) tokens = line.split() # this splits the line into chunks of characters separated by spaces Nx = int(tokens[0]) # assign the value of the first chunk of characters to Nx after interpreting them as an integer Ny = int(tokens[1]) width = float(tokens[2]) height = float(tokens[3]) D = float(tokens[4]) t = float(tokens[5]) U_x = float(tokens[6]) U_y = float(tokens[7]) S_p = float(tokens[8]) line = file.readline() # read the second line tokens = line.split() left_bc_type = int(tokens[0]) #0 is Dirichlet, 1 is Neumann right_bc_type = int(tokens[1]) top_bc_type = int(tokens[2]) bottom_bc_type = int(tokens[3]) line = file.readline() # read the third line tokens = line.split() left_bc_value = float(tokens[0]) right_bc_value = int(tokens[1]) top_bc_value = int(tokens[2]) bottom_bc_value = int(tokens[3]) # 返回所有读取到的参数 return Nx, Ny, width, height, D, t, U_x, U_y, S_p, left_bc_type, right_bc_type, top_bc_type, bottom_bc_type, left_bc_value, right_bc_value, top_bc_value, bottom_bc_value # 调用函数,传入你的txt文件路径,接收返回的参数 Nx, Ny, width, height, D, t, U_x, U_y, S_p, left_bc_type, right_bc_type, top_bc_type, bottom_bc_type, left_bc_value, right_bc_value, top_bc_value, bottom_bc_value = ReadInput("你的txt文件路径.txt") # 后续计算逻辑 N = Nx*Ny L = 1 h = np.float64(L/(N-1)) sigma = np.zeros((N,N)) b = np.zeros(N)
可选优化
你当前代码中第三行的right_bc_value、top_bc_value、bottom_bc_value强制转成了int类型,如果你需要保留txt中的浮点精度,可以把这三个变量的转换类型改为float。
内容的提问来源于stack exchange,提问作者Dylan Bull
相关产品推荐
相关产品推荐

