python从文件中随机选择一些数据

版权声明:本文为博主原创文章,未经博主允许不得转载。如若转载,请注明出处! https://blog.csdn.net/Homewm/article/details/84583863

从序列x中随机选择y条数据作为文本:

# -*- coding:utf-8 -*-

##随机挑选部分内容
# encoding:utf-8
import random
from random import randint

oldf = open('select_amigo.txt', 'r')    ###1000行
newf = open('select_amigo222.txt', 'w')   ###挑选400行
n = 0
resultList = random.sample(range(0, 1000), 400)  # sample(x,y)函数的作用是从序列x中,随机选择y个不重复的元素。

lines = oldf.readlines()
for i in resultList:
    newf.write(lines[i])
oldf.close()
newf.close()

猜你喜欢

转载自blog.csdn.net/Homewm/article/details/84583863
今日推荐