2017-02-03 44 views
0

我该如何修改此程序,以便我的列表不会继续吐出额外的文本每行?该程序应该只输出用户想要显示的单行,而不是之前添加到列表中的引号。程序将读取用户指定的文本文件,然后它将显示用户所选择的行并退出'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]: 

回答

0

从您所描述的内容中,您只希望显示与用户输入的编号对应的单行。

当前,您正在使用切片来获取之前的所有行,并包括您想要的行。在打印inputList索引中删除冒号:

elif lineChoice > 0 and lineChoice <= count: print(inputList[lineChoice - 1].strip())

要删除引号和换行字符等,使用字符串方法.strip()