Python文件系统读写练习

**
\1. 生成一个大文件ips.txt,要求1200行,
\2. 每行随机为172.25.254.0/24段的ip;
\3. 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;
**
首先创建ips.txt

import os

import random

def create_ip_file(filename):
    ip =['172.25.254.' + str(i) for i in range(0,255)]
    with open(filename,'a+') as f:
        for count in range(1200):
            f.write(random.sample(ip,1)[0] + '\n')

create_ip_file('ips.txt')

在这里插入图片描述
在这里插入图片描述
统计频率前10的ip

def sorted_by_ip(filename,count=10):
    ips_dict = dict()
    with open(filename) as f:
        for ip in f:
            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'))

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42446031/article/details/89257584