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:tt",totalChars)
print("Total digits:tt",digitCount)
print("Total spaces:tt",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()

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

相关内容

  • 没有找到相关文章

最新更新