python - 我很困惑为什么这不会打印我的文本文件
问题描述
def readText():
f = open("scores.txt", "r")
def showText():
for line in f:
w, x, y, z = line.split()
print(w, x, y, z)
readText()
showText()
解决方案
变量 f 不在 show text 函数的范围内。
def openText():
f = open("scores.txt", "r")
return f # Return the value of the file
def readAndShowText(f): # by passing the value in, you now have access to the variable
for line in f:
w, x, y, z = line.split()
print(w, x, y, z)
file = openText() # set the return value
readAndShowText(file) # pass the value into the showtext
file.close() # make sure you close it
您会注意到,正如评论中所建议的那样,我还更改了函数名称以更好地反映它们的作用。
推荐阅读
- java - 在 PreparedStatement 处获取 NullPointerException
- python - 从文件中读取文本并在 if 语句中使用
- node.js - 为什么模式字段没有使用节点 js 保存在数据库中
- jwt - 我如何添加授权:“JWT
“到 http 请求?在 Nuxt.js 中 - java - Resilience4j 使用 CompletionStage 重试
- python - 自定义 Python 日志格式化程序适用于 fileConfig 但不适用于 dictConfig?
- playframework-2.6 - Play framework 2.6 在每个请求之前运行
- robotframework - 如何将命令行变量作为参数传递给 RobotFramework Listener?
- c# - Blazor 服务器后台任务
- optimization - LLVM 能否决定 Machine Function Pass 的执行顺序?我的 Pass 生成的代码被优化弄乱了