python - Python:为什么我需要重新打开文件才能成功完成这两个操作
问题描述
这应该是基本的,但我找不到对我的问题的快速回复,对不起,如果这是双重的。
我正在编写一个小代码来学习如何操作文件并计算 txt 文件中的行数、单词数和字符数。您能否在下面的代码中解释为什么如果我没有第二次使用 another 重新加载文件with open()
,则代码无法len(f.read)
正确计数?没有它,它返回 0。欢迎提出改进代码的意见。
def wc(nomFichier):
nb_car=0
nb_words=0
nb_lig=0
with open(nomFichier) as f:
for line in f:
words = line.split()
nb_words += len(words)
nb_lig +=1
with open(nomFichier) as f: #Why I need to reload the file?
nb_car=len(f.read()) #f.read().stripignore to ignore ligne\n
f.close()
return (nb_car, nb_words, nb_lig)
解决方案
您无需重新打开文件。
def word_count(file_path):
count_chars=0
count_words=0
count_lines=0
with open(file_path) as f:
for line in f:
count_chars += len(line)
count_words += len(line.split())
count_lines +=1
return (count_chars, count_words, count_lines)
请注意,我将变量名称更改为我认为更合适的名称。
推荐阅读
- sql - 连接两个表以在 BigQuery 上创建一个大嵌套表时,如何按表 A 的所有列进行分组?
- bash - 脚本不等待 & 线程完成
- firebase - 在 firebase_messaging dev14 用户点击通知时如何打开屏幕(背景)
- firebase - Firebase 函数 HTTP 错误 404,找不到方法
- php-7 - PHP 致命错误:未捕获的错误:找不到类“Phalcon\\Db”。用于 Phalcon 4
- tomcat - 如何将 code-examples-java 转换为 war 文件以在 TOMCAT 容器下运行
- c - 我的推理错误在哪里?(递归 C)
- json - 使用通过命令行传递的路径访问 JQ 中的嵌套值
- python - Kafka 将值作为字符串发送:如何将其反序列化并使用 Python 将其转换为 JSON 对象
- html - 数据表头与正文不对齐