Python 一个统计文件行数和字符数的函数

标签 python function count

<分区>

谁能看看我到目前为止做了什么?我自己还没成功定位到问题。

def txt_file(file1):
    file1 = open('text.txt', 'r')
    linecount = 0
    charcount = 0
    for line in file1:
        linecount +=1
        for char in line:
            charcount += 1
    print "file1 contains", linecount, "lines and", charcount, "characters."
    file1.close()

最佳答案

这样更容易:

with open('text.txt') as the_file:
     data = [len(i) for i in the_file]
     line, char = len(data), sum(data)

关于Python 一个统计文件行数和字符数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29501986/

相关文章:

python - 如何在 Python 中优化基于 OpenAI 的聊天机器人的 NLP 处理时间?

识别跨列的特定事件以创建新变量

java - 我想在不同的类中使用我的计数器,但它显示为零的初始值

postgresql - 我在 postgres 中使用 group by 时出错?

python - ./zbarmodule.h :26:10: fatal error: 'zbar.h' file not found

java - 为什么 Java 和 Python 的垃圾回收方法不同?

python - cursor.fetchall() 或其他方法 fetchone() 不起作用

javascript - 函数设置为运行一次不运行

python - 如何使用if条件捕获函数返回值

php - 使用 COUNT (PHP MySQL) 添加行号并显示总数