我目前正在尝试读取文本文件,然后将其打印到Python Shell中。它完全正确地读取文件,但是当它单独读取行时它告诉我有一个AttributeError。我怎么能解决这个问题?
这是我的代码:
import time
import linecache
print("Welcome to the League Fixture Manager!")
time.sleep(3)
print("What would you like to do?")
time.sleep(1)
print("Press A to search for a fixture.")
time.sleep(0.1)
print("Press B to view Outstanding fixtures.")
time.sleep(0.1)
print("Press C to display the leader board")
time.sleep(0.1)
print("Or press Q to quit, this will exit the application.")
time.sleep(0.1)
menuOptions = input("What would you like to do? A, B, C, or Q.")
if menuOptions == 'A':
print("Searching for fixtures...")
time.sleep(3)
data = [line.strip() for line in open("Y:/Computing & Business/Students/Computing/Year 10/CA 2017 Edexcel/firesideFixtures.txt").readlines()]
lines = data.readlines()
print(data)
time.sleep(1)
print("Return to menu?")
menuReturn = input("Y or N")
if menuReturn == 'Y':
print("Press B to view outstanding fixtures.")
time.sleep(0.1)
print("Press C to display the leaderboard")
time.sleep(0.1)
print("Or press Q to exit the application.")
time.sleep(0.1)
print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
time.sleep(0.1)
menuOptions2 = input("What would you like to do? B, C, or Q?")
if menuOptions2 == 'B':
print("~~incomplete~~")
elif menuOptions2 == 'C':
print("~~incomplete~~")
elif menuOptions2 == 'Q':
print("Exiting Application...")
time.sleep(1)
exit()
elif menuReturn == 'N':
print("Exiting Application...")
time.sleep(2)
exit()
elif menuOptions == 'B':
print("~~incomplete~~")
elif menuOptions == 'C':
print("~~incomplete~~")
elif menuOptions == 'Q':
print("Exiting Applicaion...")
time.sleep(2)
exit()
这就是我所接受的:
Welcome to the League Fixture Manager!
What would you like to do?
Press A to search for a fixture.
Press B to view Outstanding fixtures.
Press C to display the leader board
Or press Q to quit, this will exit the application.
What would you like to do? A, B, C, or Q.A
Searching for fixtures...
Traceback (most recent call last):
File "E:\Python\Python Work\League\League3.py", line 20, in <module>
lines = data.readlines()
AttributeError: 'list' object has no attribute 'readlines'
答案 0 :(得分:0)
您正在尝试将readlines
应用于列表。在您的示例中,data
已经是包含文件行的列表。这一行:
lines = data.readlines()
是多余的。你可以删除它。更多,请注意方法readlines()
在使用readline()
和已经的EOF之前读取的事实会返回包含这些行的列表。
此外,我建议您在处理文件时使用with()
:
with open(some_file) as f:
....
使用with
语句的优点是无论嵌套块如何退出,都可以保证关闭文件(您没有做过的事情)。如果在块结束之前发生异常,它将在异常被外部异常处理程序捕获之前关闭该文件。
根据您的打印请求,只需循环遍历列表并将其打印出来:
for line in data:
print(line)
我建议您阅读官方Python documentation。