转:
#encoding=utf-8
import random
from sets import Set
def copyfile(srcfile, dstfile, linenum):
"""
get linenum different lines out from srcfile at random
and write them into dstfile
"""
result = []
ret = False
try:
srcfd = open(srcfile,'r')
except IOError:
print 'srcfile doesnot exist!'
return ret
try:
dstfd = open(dstfile,'w')
except IOError:
print 'dstfile doesnot exist!'
return ret
srclines = srcfd.readlines()
srclen = len(srclines)
while len(Set(result)) < int(linenum):
s = random.randint(0,srclen-1)
result.append(srclines[s])
for content in Set(result):
dstfd.write(content)
srcfd.close()
dstfd.close()
ret = True
return ret
if __name__ == "__main__":
srcpath = raw_input('input srcfile path')
dstpath = raw_input('input dstfile path')
linenum = raw_input('input linenum')
print copyfile(srcpath,dstpath,linenum)