Python文本文件列表没有划分

时间:2017-02-03 02:30:04

标签: python list text

我如何修改此程序,以便我的列表不会继续吐出每行的额外文本?程序应该只输出用户想要显示的单行而不是之前添加到列表中的引号。程序将读取用户指示的文本文件,然后它将显示用户选择的行并退出“0”输入。 这是在python中

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]:

2 个答案:

答案 0 :(得分:0)

Python String strip()方法

示例用法

#!/usr/bin/python

str = "0000000this is string example....wow!!!0000000";
print str.strip( '0' )

输出:

this is string example....wow!!!

示例来自https://www.tutorialspoint.com/python/string_strip.htm

答案 1 :(得分:0)

根据您的描述,您只想显示与用户输入的数字对应的单行。

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

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

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