Python一个对文件中的行和字符进行计数的函数 - python

Closed. This question does not meet Stack Overflow guidelines。它当前不接受答案。

想改善这个问题吗?更新问题,以使为on-topic。

5年前关闭。

Improve this question

有人可以看看我到目前为止所做的吗?我自己尚未成功找到问题所在。

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()

python大神给出的解决方案

这样更容易:

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