Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python I';我不明白这为什么会赢';不要打印我的文本文件_Python - Fatal编程技术网

Python I';我不明白这为什么会赢';不要打印我的文本文件

Python I';我不明白这为什么会赢';不要打印我的文本文件,python,Python,变量f不在show text函数的作用域内 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() 您会注意到,我还更改了函数名,以更好地反映它们的功能,如注释中所示。直截了当的回答: def openText():

变量f不在show text函数的作用域内

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

您会注意到,我还更改了函数名,以更好地反映它们的功能,如注释中所示。

直截了当的回答:

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
双功能方法:

filename = input("Enter path to file:")
def getLines(filename):
   f = open(filename, "r")
   for line in f.readlines():
       w,x,y,z = line.split()
       print(w,x,y,z)
   f.close()

在这篇文章中,所有好的答案,你遇到的主要问题是范围

def readText():
inputText=[]#空列表
#打开文件
以open('scores.txt','r')作为分数:
#遍历文件并将每个分数添加到列表中
对于在线分数:
inputText.append(行)
返回inputText#返回列表
def showText():
outputText=readText()#从readText()获取列表
#遍历列表并输出每个分数
对于outputText中的行:
打印(行)
showText()
我的回答显示了另一种完成任务的方法,如果分数在一个用新行分隔的文件中——尽管由于“冗余变量”的原因,这不是最佳解决方案,但使用Python有很多方法来完成任务。祝你以后的学习好运

编辑:如果分数在一行中以逗号分隔,则另一种解决方案:

def readText():
以open('scores.txt','r')作为分数:
对于在线分数:
inputText=line.split(',')
返回输入文本
def showText():
outputText=readText()
对于outputText中的行:
打印(行)
showText()

f
不在
showText()
范围内,两个函数都需要修复,或者将第二个函数折叠为第一个函数,没有理由说应该有一个用于打开,一个用于阅读。@FishingCode我的教授说我们必须使用至少两个函数。从readText返回f,然后将其传递到showText中。注意变量名,尽管函数名与它们所做的并不匹配。第一个函数不读取文本。它只是打开文件。第二个函数不仅显示文本,还读取文本。也许您应该更改第一个函数以实际读取文件的内容,将其存储在列表中,然后传递到
showText
。读取后不要忘记关闭文件。从文件读取意味着将文件内容拉入程序。打开文件只是为读取做准备。这些函数名与函数的功能不匹配。它可能修复了主要的bug,但忽略了代码中的其他主要问题。读取文件后,您还忘了关闭它。@Tom,我想我已经修复了所有这些问题,您可能想看看我是否遗漏了任何内容,或者引入了其他问题。变量
text
用于第一个函数,更改第二个函数中调用的变量以提高清晰度:-)这样更好,但是您引入了稍微不同的线路处理方式。如果您恢复到
split
方法,可能会非常完美。
def readFile():
   f = open("/path/to/filename/scores.txt", "r")
   return f

def getLines(f):
    for line in f:
      w, x, y, z  = line.split()
      print(w, x, y, z)
    f.close()

if __name__ == "__main__":

   getMyLines = readFile()
   getLines(getMyLines)