python 随机读取txt一行数据

def User_Agent():
    txt = open('Pc-ua.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'Pc-ua.txt', i)
    print(line)
    return line
原文地址:https://www.cnblogs.com/chenlizhi/p/13804781.html