樓上說的不全對,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)