代码块:
from collections import Iterable
f = open('/tmp/passwd')
print(isinstance(f,Iterable))
for i,item in enumerate(f):
if i == 10:
break
print(i,item)
示例及运行结果:
题目要求:
1. 生成一个大文件ips.txt,要求1200行
每行随机为172.25.254.0/24段的ip;
2. 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;
代码块:
import random
def create_ip(filename):
ip = ['172.25.254.' + str(i) for i in range(1,255)]
with open(filename,'a+') as f:
for i in range(1200):
f.write(random.sample(ip,1)[0] + '\n')
create_ip('ips.txt')
def sorted_by_ip(filename,count=10):
ips_dict = dict()
with open(filename) as f:
for ip in f:
ip = ip.strip()
if ip in ips_dict:
ips_dict[ip] += 1
else:
ips_dict[ip] = 1
sorted_ip = sorted(ips_dict.items(),key=lambda x:x[1],reverse=True)[:count]
return sorted_ip
print(sorted_by_ip('ips.txt'))