python计算文件中的字符

时间:2015-08-29 23:44:50

标签: file python-3.x

我试图找出如何计算文件中有多少个字符,这是我的代码到目前为止:

def file_size(filename):
num_chars = 0
open(filename, 'r')
num_chars += len(filename)

print(file_size('data.txt')) 

4 个答案:

答案 0 :(得分:2)

您可以在file.read()之后使用len()

def file_size(filename):
   with open(filename) as f:
      return len(f.read())

print(file_size('data.txt'))

答案 1 :(得分:1)

要获取文件的大小(无需阅读整个文件),请使用os.stat;

import os

def filezise(path):
    res = os.stat(path);
    return res.st_size

该文件包含多少个字符,取决于文件中的内容。

  • 如果是二进制数据,则单词"字符"没什么意义。虽然它经常被解释为字符是字节。
  • 纯ASCII文本和其他编码,例如latin-1每个字符使用一个字节。
  • 其他编码(如UTF-32)每个字符使用多个字节,但它们对每个字符使用相同的字节数。
  • 如果文件使用variable-width encoding,例如UTF-8和UTF-16,则必须检查整个内容以解读字符数。

答案 2 :(得分:1)

f = open(file_name)
text = f.readlines()
print(sum(map(len, text)))

答案 3 :(得分:0)

我使用嵌套的for循环来计算给定文件中的字符数。

#open file for reading
file = open("data.txt", "r")
#set count variable equal to 0
count = 0
#outer loop iterates over each line in file.
for line in file:
    #inner loop iterates over each individual character in each line.
    for character in line:
        #check to see if that individual character is in fact a letter use str.isalpha()
        if character.isalpha():
           #if condition is true count must increase by 1
           count += 1
print("they're {} characters in such file".format(count))
#Don't forget to close the file! I tend to close all file from which they have been opened.
file.close()