【问题标题】:Reading the file returns nothing (python) [duplicate]读取文件不返回任何内容(python)[重复]
【发布时间】:2021-09-23 11:26:08
【问题描述】:

这是我的简单音乐测验代码的一部分。但是,每当我运行 file.readline() 时,它都会返回一个空白区域。有一个名为 storage.txt 的文本文件,其中包含数据。我尝试过使用 file.seek()、file.read() 和 file.readlines(),但到目前为止还没有一个允许我打印特定的行。

points = 0
question_number = 0

file = open("storage.txt","r")
while True: 
 question_number = question_number + 1
 keyword = file.readline(question_number)
 print("Who made this song?")
 answer = input(keyword)
 if answer == file.readline(question_number+1):
  print("You got it right, 1 point for you!")
  points += 1
 else:
  print("You lost with",points,"points.")
  break

file.close()
print("All done.")

【问题讨论】:

标签: python


【解决方案1】:

这里file.readline()的用法是错误的。检查该函数应该获取哪些参数。 Maybe this could helpreadline() 读取文件的下一行,而不是参数中指定的行。该参数实际上是size,即该行要读取多少字节。如果您想阅读特定的行,我建议您这样做 -

keyword = file.readlines()[question_number]

您可能想参考this 了解如何使用readlines() 函数。

无论如何,我建议您将文件变量命名为其他名称,因为文件是一个保存的单词。将其命名为 my_filesong_titles_file 或任何其他有意义的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2016-08-10
    • 2013-02-18
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多