我试图找出如何计算文件中有多少个字符,这是我的代码到目前为止:
def file_size(filename):
num_chars = 0
open(filename, 'r')
num_chars += len(filename)
print(file_size('data.txt'))
答案 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
该文件包含多少个字符,取决于文件中的内容。
答案 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()