1. 程式人生 > >python從檔案中隨機選擇一些資料

python從檔案中隨機選擇一些資料

從序列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()