我该如何修改此程序,以便我的列表不会继续吐出额外的文本每行?该程序应该只输出用户想要显示的单行,而不是之前添加到列表中的引号。程序将读取用户指定的文本文件,然后它将显示用户所选择的行并退出'0'输入。 这是在pythonPython文本文件列表不分行
import string
count = 0
#reads file
def getFile():
while True:
inName = input("Please enter file name: ")
try:
inputFile = open(inName, 'r')
except:
print ("I cannot open that file. Please try again.")
else:
break
return inputFile
inputFile = getFile()
inputList = inputFile.readlines()
for line in inputList:
count = count + 1
print("There are", count, "lines.")
while True:
lineChoice = int(input("Please select line[0 to exit]: "))
if lineChoice == 0:
break
elif lineChoice > 0 and lineChoice <= count:
print(inputList[:lineChoice - 1])
else:
print("Invalid selection[0 to exit]")
输出:
Please enter file name: quotes.txt
There are 16 lines.
Please select line[0 to exit]: 1
[]
Please select line[0 to exit]: 2
['Hakuna Matata!\n']
Please select line[0 to exit]: 3
['Hakuna Matata!\n', 'All our dreams can come true, if we have the courage to pursue them.\n']
Please select line[0 to exit]: