簡體   English   中英

Python文本文件到列表不分割

[英]Python Text file to List not dividing up

我將如何修改此程序,以使我的列表不會一直吐出每行多余的文本? 該程序應只輸出用戶要顯示的單行,而不是以前添加到列表中的引號。 該程序將讀取用戶指示的文本文件,然后將為用戶顯示選定的行並退出“ 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]:

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

根據您的描述,您只想顯示與用戶輸入的號碼相對應的單行。

當前,您正在使用切片來獲取所需行之前(包括該行)的所有行。 在打印的inputList索引中刪除冒號:

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

要刪除引號和換行符等,請使用字符串方法.strip()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM