楼上说的不全对,os.listdir(path)会把路径下所有文件和文件夹都返回,计算文件数量要筛选路径下的文件和文件夹
importos
ls=os.listdir(path)
count=0
foriinls:
ifos.path.isfile(os.path.join(path,i)):
count+=1
printcount
2. python计算txt中特定内容的数量。
count=0
withopen('filename.txt')asfile:
forlineinfile.readlines():
ifline.startswith('label:1'):
print(line)
count+=1
print('label:1行数为:',count)
3. 如何用python统计一个路径下的文件总数
刚好刚才写了一个
defget_dir_info(dir_path,deep=0,info=None):
ifinfoisNone:
info={'deep':0,'deep_dir':'','file_num':0,'dir_num':0}
ifdeep>info['deep']:
info['deep']=deep
info['deep_dir']=dir_path
file_list=os.listdir(dir_path)
forfileinfile_list:
file_path=os.path.join(dir_path,file)
ifos.path.isdir(file_path):
info['dir_num']+=1
get_dir_info(file_path,deep=deep+1,info=info)
else:
info['file_num']+=1
ifdeep==0:
returninfo
if__name__=='__main__':
dir_path="D:\Tools\WebStorm2016\plugins"
s=time.time()
d=get_dir_info(dir_path)
print("{}".format(time.time()-s))
print(d)
#所有的深度是基于给出的文件夹统计的
#deep_dir比较鸡肋,因为如果有多个相同深度的文件夹就会替换掉只剩一个
#可以自行去掉这个功能
#deep:最深的层数
#deep_dir:最深的路径名称
#dir_num:文件夹数量
#file_num:文件数量
'''
0.21001195907592773
{'deep':12,'deep_dir':'D:\Tools\WebStorm2016\plugins\spy-js\server\node_moles\istanbul\node_moles\resolve\test\resolver\biz\node_moles\garply\lib','file_num':6325,'dir_num':1113}
'''
4. python 如何读取txt 并输出统计数量
#-*-coding:utf-8-*-
importre
fruits_and_price_cp=re.compile('([a-z]+)([0-9]+)')
fruits_name_cp=re.compile('[a-z]+')
withopen('/home/js/Desktop/fruits.txt')asf:
content=f.read()
print(content)
fandp=fruits_and_price_cp.findall(content)#水果名和价格
#[('apple','20'),('banana','30'),('orange','40'),('apple','50'),('banana','70'),('orange','10')]
fruits_name_set=set(fruits_name_cp.findall(content))#集合去重复
#fruits_name_set--->set(['orange','apple','banana'])
fruits_name=sorted(fruits_name_set)#转化为列表排序
#fruits_name--->['apple','banana','orange']
fruits_dict={}
fornameinfruits_name:#构建{水果名:价格}字典
fruits_dict.setdefault(name,0)
#fruits_dict--->{'apple':0,'banana':0,'orange':0}
#求水果相应的价格
fornameinfruits_dict:#开始循环水果名字典
forfnpinfandp:#循环水果名和价格列表
ifname==fnp[0]:
fruits_dict[name]+=int(fnp[1])#如果列表里水果名与字典key一样,就把价格转化为int,加入到字典值
forfninfruits_name:
print('{}{}'.format(fn,fruits_dict[fn]))
5. python读文件统计次数和求和怎么写
#!/usr/bin/envpython>python -u ".py"
#coding:utf-8
importre
patt=re.compile(r"""
(?P<id>S+)
s+
(?P<category>S+)
s+
(?P<number>d+)
""",re.I|re.U|re.X)
context="""
A122
A144
A233
B122
B344
B455
C111
C422
"""
collects={}
forminfilter(None,map(patt.match,context.splitlines())):
d=m.groupdict()
collects.setdefault((d["id"],d["category"]),[]).append(int(d["number"]))
for(id,category)insorted(collects):
printid,category,sum(collects[(id,category)])
6. 如何用python计算文件的字数
#这边的TXT需要改动
flies=open('MyFather.txt','r')
lines=flies.readlines()
lens=len(lines)
dicts={}
#定义一个方法,获取单词,去掉前后标点符号
defgetWord(str):
temp=list(str)
num=len(temp)
word=[]
foriinrange(num):
iftemp[i]!=','andtemp[i]!='.'andtemp[i]!='"':
word.append(temp[i])
else:
return''.join(word).lower()
foriinrange(lens):
word=lines[i].split()
len_num=len(word)
fortinrange(len_num):
words=GetWord(word[t])
ifnotdicts.has_key(words):
dicts=dicts.fromkeys([words],1)
dicts[words]=1
else:
dicts[words]+=1
flies.close()
dicts_list=dicts.items()
num=len(dicts_list)-1
forindinrange(num):
printdicts_list[ind]
这个一个自己写的统计一个纯英文TXT文档中每个单词出现的次数。你看着自己改下吧。
7. python如何统计所有文本文件的行数
with open(file) as f:
text=f.read()
length=len(text.splitlines())
8. 如何获取目录下的文件数(一行Python)
如果想把该目录下所有的文件都统计出来,包括子目录、子目录的子目录。。。
可以使用os.walk来找出目录下所有的文件
import os
print sum([len(x) for _, _, x in os.walk(os.path.dirname("test"))])
#test是目录名
os.walk会递归遍历指定目录下的文件,返回值分别为当前文件夹完整路径,当前文件夹中的文件夹和文件夹中的文件。我们只需要文件,所以其他的都不取出来了,直接使用"_"占位就行了。
如果只是想统计出当前目录下的文件,不包括子目录的。就使用os.listdir,只统计是文件的个数:
len([x for x in os.listdir(os.path.dirname(__file__)) if os.path.isfile(x)])
9. python 统计文本中字母个数
l=0
withopen('file.txt','r')asfr:
txt=fr.read()
forcintxt:
ifcin'':
l+=1
print(l)