首页 > 解决方案 > 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)

标签: python

解决方案


您无需重新打开文件。

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)

请注意,我将变量名称更改为我认为更合适的名称。


推荐阅读