2015-08-29 192 views
1

我试图找出如何计算有多少个字符中有一个文件的字符计数是迄今为止我的代码:蟒蛇在文件

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

print(file_size('data.txt')) 
+0

可能重复(http://stackoverflow.com/questions/8931767/python-number-of-characters-in-text-file) –

回答

2

您可以简单地使用len()后你file.read()

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

print(file_size('data.txt')) 
+1

你大概意思:'打开(文件名)为f';)除此之外,这应该工作得很好,再加上一个。 – alfasin

+0

@alfasin好,赶快,谢谢。修复。 :) – Sait

1

获取文件的大小(而不必读取整个事情),使用os.stat;

import os 

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

文件中包含多少字符,取决于什么是在文件中。

  • 如果是二进制数据,那么“characters”这个词就没什么意义了。虽然它经常被解释为字符是字节。
  • 纯ASCII文本和其他编码例如拉丁语-1使用每个字符一个字节。
  • 其他编码(如UTF-32)每个字符使用多个字节,但它们对每个字符使用相同数量的字节。
  • 如果文件使用了诸如UTF-8和UTF-16的variable-width encoding,则必须检查整个内容以解密字符数量。
+0

OP没有提及该文件是否有unicode –

+0

st_size =文件大小,以字节为单位,而不是字符数。 – alfasin

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

问题中有一个'python-3.x'标签,所以你可能想把括号放到你的'print()'中。 ;)除此之外,这应该工作得很好,再加上一个。 – Sait

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() 
的[Python的:在文本文件中的字符数]