Python实现遍历数据库并获取key的值

yipeiwu_com6年前Python基础

遍历Redis数据库中有以格式为PREFIX_*的按照key-value方式存储的key,并打印其值.

遍历使用SCAN,因为KEYS PREFIX_*可能会造成Redis长时间阻塞。
查询使用pipeline减少交互,提高效率。

import redis
import hiredis

pool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0)
r = redis.Redis(connection_pool=pool)

pipe = r.pipeline()
pipe_size = 100000

len = 0
key_list = []
for key in r.scan_iter(match='PREFIX_*', count=100000):
key_list.append(key)
pipe.get(key)
 if len < pipe_size:
 len += 1
else:
 for (k, v) in zip(key_list, pipe.execute()):
 print k, v
 len = 0
 key_list = []

for (k, v) in zip(key_list, pipe.execute()):
 print k, v

附上其他网页的代码,参考下吧

# filename itertaorfilefolder 
import os 
import os.path

filePath = raw_input('Enter filepath : ')

#遍历文件夹 
#三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字 
for parent ,dirnames , filenames in os.walk(filePath): 
  #输出文件夹信息 
  for dirname in dirnames: 
    print 'parent is :'+parent 
    print 'dirname is '+ dirname 
  #输出文件信息 
  for filename in filenames : 
    print 'parent is :'+parent 
    print 'filename is :' + filename 
    #输出文件路径信息 
    currentPath = os.path.join(parent,filename) 
    print 'the fulll name of the file is :'+ currentPath 
    filesize = os.path.getsize(currentPath)/1024/1024 
    print 'the file size is : %.3f MB' %(filesize) 
    #删除大于50m的文件 
    if filesize > 50: 
      delete = raw_input(' are you sure to delete ?') 
      if delete == 'yes': 
        os.remove(currentPath)

以上所述就是本文的全部内容了,希望大家能够喜欢。

相关文章

对Python3中列表乘以某一个数的示例详解

在Python列表操作中:列表乘以某一个数,如list2 = list1 * 2 得到一个新的列表是list1的元素重复n次,且list1不改变。 但运行如下代码时,得到的新列表b中,b...

Python绘图Matplotlib之坐标轴及刻度总结

Python绘图Matplotlib之坐标轴及刻度总结

学习https://matplotlib.org/gallery/index.html 记录,描述不一定准确,具体请参考官网 Matplotlib使用总结图 import ma...

Python基于dom操作xml数据的方法示例

Python基于dom操作xml数据的方法示例

本文实例讲述了Python基于dom操作xml数据的方法。分享给大家供大家参考,具体如下: 1、xml的内容为del.xml,如下 <?xml version="1.0...

Python入门教程2. 字符串基本操作【运算、格式化输出、常用函数】 原创

前面简单介绍了Python基本运算,这里再来简单讲述一下Python字符串相关操作 1. 字符串表示方法 >>> "www.jb51.net" #字符串使用单引号(...

浅谈Python处理PDF的方法

浅谈Python处理PDF的方法

处理pdf文档 第一、 从文本中提取文本 第二、 创建PDF 两种方法 #使用PdfFileWriter import PyPDF2 pdfFiles = [] for fi...