首页 > 解决方案 > 我很困惑为什么这不会打印我的文本文件

问题描述

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()

标签: python

解决方案


变量 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

您会注意到,正如评论中所建议的那样,我还更改了函数名称以更好地反映它们的作用。


推荐阅读