Readlines 只读取我的文本文件中的第一行

时间:2021-02-19 16:17:20

标签: python readline readlines

我正在尝试转换一个程序,该程序接受用户字符串输入并定义字符串有多少个小写、大写、数字和字符。进入读取文本文件并输出小写/大写/数字/和字符的程序。我的大部分程序都像打印输出一样快速完成,但我不明白为什么我的 .readlines() 没有读取文件中的每一行并分析它们,而不是只查看第一行。

def countList( myList ):
    if len(myList) == 0:
        return 0

    #variables
    totalChars = 0
    digitCount = 0
    spaceCount = 0
    alphaCount = 0
    upperCase  = 0
    lowerCase  = 0
    notDigitOrAlphaOrSpace = 0

    
    for ch in myList:     
        totalChars+=1
        if ch.isdigit():
            digitCount+=1
        elif ch.isspace():
            spaceCount+=1
            if ch.isupper():
                upperCase+=1
            else:
                lowerCase+=1
        else:
            notDigitOrAlphaOrSpace+=1
    #output
    print("Total characters:\t\t",totalChars)
    print("Total digits:\t\t",digitCount)
    print("Total spaces:\t\t",spaceCount)
    print("\tAlpha upper:\t",upperCase)
    print("\tAlpha lower:\t", lowerCase)
    print("Not an alpha or digit or space:\t", notDigitOrAlphaOrSpace)
    return totalChars
def main():
   
    myFile = open('text.txt','r')
    myList = myFile.readline()
    # call our count the characters function
    numChars = countList(myList)

    
    if numChars > 0:
        print("Your file was",numChars,"characters long")
    else:
        print("Your file had no characters.")

main()

1 个答案:

答案 0 :(得分:3)

调用 file.readlines() 而不是 readline() 来读取所有行

相关问题