python基础===随机打印txt文件中的某一行

def find():
    txt = open(r'F:send1.txt','rb')
    data = txt.read().decode('utf-8')      #python3一定要加上这句不然会编码报错!
    txt.close()
    i = random.randint(1, 121)            #我的文档我数了一下是120行,这里就是1~121
    ###得到对应的i行的数据
    line=linecache.getline(r'F:send1.txt',i)

或者升级一下:

def find():
    txt = open(r'F:send1.txt','rb')
    data = txt.read().decode('utf-8')      #python3一定要加上这句不然会编码报错!
    txt.close()

#获取txt的总行数! n = data.count(' ') print("总行数",n) #选取随机的数 i = random.randint(1, (n+1)) print("本次使用的行数",i) ###得到对应的i行的数据 line=linecache.getline(r'F:send1.txt',i)

顺便提一下


如果你也喜欢Python 这里有一群Python爱好者汇集在此。

关注微信公众号:【软件测试技术】,回复 888,获取QQ群号。 

原文地址:https://www.cnblogs.com/botoo/p/7356737.html