python如何随机读取一行
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python如何随机读取一行相关的知识,希望对你有一定的参考价值。
有一个txt里面几百万行,请问用python如何随机的读取其中一行呢?
#!/usr/bin/env python# coding: utf-8
def getfilelines(filename, eol='\\n', buffsize=4096):
"""计算给定文件有多少行"""
with open(filename, 'rb') as handle:
linenum = 0
buffer = handle.read(buffsize)
while buffer:
linenum += buffer.count(eol)
buffer = handle.read(buffsize)
return linenum
def readtline(filename, lineno, eol="\\n", buffsize=4096):
"""读取文件的指定行"""
with open(filename, 'rb') as handle:
readedlines = 0
buffer = handle.read(buffsize)
while buffer:
thisblock = buffer.count(eol)
if readedlines < lineno < readedlines + thisblock:
# inthisblock: findthe line content, and return it
return buffer.split(eol)[lineno - readedlines - 1]
elif lineno == readedlines + thisblock:
# need continue read line rest part
part0 = buffer.split(eol)[-1]
buffer = handle.read(buffsize)
part1 = buffer.split(eol)[0]
return part0 + part1
readedlines += thisblock
buffer = handle.read(buffsize)
else:
raise IndexError
def getrandomline(filename):
"""读取文件的任意一行"""
import random
return readtline(
filename,
random.randint(0, getfilelines(filename)),
)
if __name__ == "__main__":
import sys
import os
if len(sys.argv) == 1:
print getrandomline("/home/tim/documents/users.csv")
else:
for f in filter(os.path.isfile, sys.argv[1:]):
print getrandomline(f)
对于超大文件建议用逐行或分块的方式处理;逐行处理可能慢一些,但编码更简单清晰一点;上面给出的是按分块方式处理的。
#use:python xx.py file
import random
import sys
def random_read(read_file):
count = 0
for count, line in enumerate(open('read_file','rU')):
count += 1
line = random.randint(0,count-1)
f = open('read_file','r').readlines()[line]
print f
def main():
if len(sys.argv) != 2:
print 'use: %s filename' % sys.argv[0]
sys.exit(1)
read_file = sys.argv[1]
random_read(read_file)
if __name__ == "__main__":
main()追问
对不起 我想要python3的,另外能不用python xx.py file这种命令行形式吗?直接open('test.txt。改好后我再给你加分
追答改最后面就行了
if __name__ == "__main__":
random_read('test.txt') #最好带路径
开头加个这个#!/usr/bin/env python 运行的时候直接./xx.py就可以了
python3应该库跟语法都不一样吧
这个逻辑很简单 你可以自己尝试一下变成python3的代码:)
#coding=utf-8
#! /usr/bin/python
import random
import linecache
def hello():
count = len(open('hello.txt','rU').readlines())#获取行数
hellonum=random.randrange(1,count, 1)#生成随机行数
return linecache.getline('hello.txt',hellonum)#随机读取某行
if __name__ == "__main__":
hello()
参考技术C import random
f=open('a.txt')
randomLineNumber=int(raw_input('Please input a random line no.:').strip())
for i in range(randomLineNumber):
x=f.tell()# get the current position of the file
f.readline()
if x==f.tell():
print "Error: The file only has %d lines, so, "%i+\\
"it's impossible to get the line you want!!!"
exit(1)
print f.readline()[:-1]
f.close() 参考技术D 试试这个方法:http://computer.uoh.edu.cn/python/634.html
以上是关于python如何随机读取一行的主要内容,如果未能解决你的问题,请参考以下文章
读取文件时Python中的UnicodeDecodeError,如何忽略错误并跳转到下一行?