我试图找出如何计算有多少个字符中有一个文件的字符计数是迄今为止我的代码:蟒蛇在文件
def file_size(filename):
num_chars = 0
open(filename, 'r')
num_chars += len(filename)
print(file_size('data.txt'))
我试图找出如何计算有多少个字符中有一个文件的字符计数是迄今为止我的代码:蟒蛇在文件
def file_size(filename):
num_chars = 0
open(filename, 'r')
num_chars += len(filename)
print(file_size('data.txt'))
您可以简单地使用len()
后你file.read()
。
def file_size(filename):
with open(filename) as f:
return len(f.read())
print(file_size('data.txt'))
获取文件的大小(而不必读取整个事情),使用os.stat
;
import os
def filezise(path):
res = os.stat(path);
return res.st_size
文件中包含多少字符,取决于什么是在文件中。
OP没有提及该文件是否有unicode –
st_size =文件大小,以字节为单位,而不是字符数。 – alfasin
f = open(file_name)
text = f.readlines()
print(sum(map(len, text)))
问题中有一个'python-3.x'标签,所以你可能想把括号放到你的'print()'中。 ;)除此之外,这应该工作得很好,再加上一个。 – Sait
我使用的嵌套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的:在文本文件中的字符数]
可能重复(http://stackoverflow.com/questions/8931767/python-number-of-characters-in-text-file) –