您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在不检查空行的情况下在Python中进行while循环直到文件结束?

如何在不检查空行的情况下在Python中进行while循环直到文件结束?

不要以这种方式遍历文件。而是使用for循环。

for line in f:
    vowel += sum(ch.isvowel() for ch in line)

实际上,您的整个程序就是:

VOWELS = {'A','E','I','O','U','a','e','i','o','u'}
# I'm assuming this is what isvowel checks, unless you're doing something
# fancy to check if 'y' is a vowel
with open('filename.txt') as f:
    vowel = sum(ch in VOWELS for line in f for ch in line.strip())

就是说,如果while由于某些误导的原因您真的想继续使用循环:

while True:
    line = f.readline().strip()
    if line == '':
        # either end of file or just a blank line.....
        # we'll assume EOF, because we don't have a choice with the while loop!
        break
python 2022/1/1 18:26:58 有322人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶