Python统计用户输入文件中How开头行数返回0的问题咨询
错误原因
- 变量误用:你把用户输入的文件名字符串存入了
fhand变量,open()执行后返回的可遍历文件对象存入了fname变量,但你后续写的循环是遍历fhand(也就是文件名的字符串)。遍历字符串只会逐个取出单个字符,不可能匹配到以"How"开头的行,所以计数始终为0。 - 异常逻辑不全:文件打开失败打印提示后,后续计数代码仍会执行,会触发不必要的报错。
修复方法
直接把循环的遍历对象改为打开后的文件对象fname,同时补全异常后的退出逻辑即可,修正后的基础代码如下:
fhand = input("enter the file name") try: fname = open(fhand) except: print("can't open the file") exit() count = 0 for line in fname: if line.startswith("How"): count = count + 1 print("There are", count, "lines in this file starting with 'How'.")
可选优化
如果需要兼容行首有空格、制表符的场景,可以把判断条件改为if line.lstrip().startswith("How"),自动去除行首空白后再匹配。
更推荐使用with上下文管理器自动处理文件的关闭,避免资源泄露,优化后的代码如下:
fhand = input("enter the file name") count = 0 try: with open(fhand, 'r', encoding='utf-8') as f: for line in f: if line.startswith("How"): count += 1 except: print("can't open the file") exit() print(f"There are {count} lines in this file starting with 'How'.")
内容的提问来源于stack exchange,提问作者Sohail Hassan
相关产品推荐
相关产品推荐

