python文件排序的方法总结


Posted in Python onSeptember 13, 2020

在python环境中提供两种排序方案:用库函数sorted()对字符串排序,它的对象是字符;用函数sort()对数字排序,它的对象是数字,如果读取文件的话,需要进行处理(把文件后缀名‘屏蔽')。

(1)首先:我测试的文件夹是/img/,里面的文件都是图片,如下图所示:

python文件排序的方法总结

(2)测试库函数sorted(),直接贴出代码:

import numpy as np
import os
 
img_path='./img/'
 
img_list=sorted(os.listdir(img_path))#文件名按字母排序
img_nums=len(img_list)
for i in range(img_nums):
    img_name=img_path+img_list[i]
    print(img_name)

运行效果如下:

python文件排序的方法总结

从图片可以清晰的看出,文件名是按字符排序的。

(3)测试函数sort(),代码:

import numpy as np
import os
img_path='./img/'
 
img_list=os.listdir(img_path)
img_list.sort()
img_list.sort(key = lambda x: int(x[:-4])) ##文件名按数字排序
img_nums=len(img_list)
for i in range(img_nums):
    img_name=img_path+img_list[i]
    print(img_name)

运行效果如下:

python文件排序的方法总结

可以看出,文件名是按数字排序的;顺便提下,sort函数中用到了匿名函数(key = lambda x:int(x[:-4])),其作用是将后缀名'.jpg'“屏蔽”(因为‘.jpg'是4个字符,所以[:-4]的含义是从文件名开始到倒数第四个字符为止),具体看python的匿名函数和数组取值方式。

实例扩展:

import gzip
import os
from multiprocessing import Process, Queue, Pipe, current_process, freeze_support
from datetime import datetime
def sort_worker(input,output):
 while True:
 lines = input.get().splitlines()
 element_set = {}
 for line in lines:
  if line.strip() == 'STOP':
   return
  try:
   element = line.split(' ')[0]
   if not element_set.get(element): element_set[element] = ''
  except:
   pass
 sorted_element = sorted(element_set)
 #print sorted_element
 output.put('\n'.join(sorted_element))
def write_worker(input, pre):
 os.system('mkdir %s'%pre)
 i = 0
 while True:
  content = input.get()
  if content.strip() == 'STOP':
   return
  write_sorted_bulk(content, '%s/%s'%(pre, i))
  i += 1
def write_sorted_bulk(content, filename):
 f = file(filename, 'w')
 f.write(content)
 f.close()
def split_sort_file(filename, num_sort = 3, buf_size = 65536*64*4):
 t = datetime.now()
 pre, ext = os.path.splitext(filename)
 if ext == '.gz':
  file_file = gzip.open(filename, 'rb')
 else:
  file_file = open(filename)
 bulk_queue = Queue(10)
 sorted_queue = Queue(10)
 NUM_SORT = num_sort
 sort_worker_pool = []
 for i in range(NUM_SORT):
  sort_worker_pool.append( Process(target=sort_worker, args=(bulk_queue, sorted_queue)) )
  sort_worker_pool[i].start()
 NUM_WRITE = 1
 write_worker_pool = []
 for i in range(NUM_WRITE):
  write_worker_pool.append( Process(target=write_worker, args=(sorted_queue, pre)) )
  write_worker_pool[i].start()
 buf = file_file.read(buf_size)
 sorted_count = 0
 while len(buf):
  end_line = buf.rfind('\n')
  #print buf[:end_line+1]
  bulk_queue.put(buf[:end_line+1])
  sorted_count += 1
  if end_line != -1:
   buf = buf[end_line+1:] + file_file.read(buf_size)
  else:
   buf = file_file.read(buf_size)
 for i in range(NUM_SORT):
  bulk_queue.put('STOP')
 for i in range(NUM_SORT):
  sort_worker_pool[i].join()
  
 for i in range(NUM_WRITE):
  sorted_queue.put('STOP')
 for i in range(NUM_WRITE):
  write_worker_pool[i].join()
 print 'elasped ', datetime.now() - t
 return sorted_count
from heapq import heappush, heappop
from datetime import datetime
from multiprocessing import Process, Queue, Pipe, current_process, freeze_support
import os
class file_heap:
 def __init__(self, dir, idx = 0, count = 1):
  files = os.listdir(dir)
  self.heap = []
  self.files = {}
  self.bulks = {}
  self.pre_element = None
  for i in range(len(files)):
   file = files[i]
   if hash(file) % count != idx: continue
   input = open(os.path.join(dir, file))
   self.files[i] = input
   self.bulks[i] = ''
   heappush(self.heap, (self.get_next_element_buffered(i), i))
 def get_next_element_buffered(self, i):
  if len(self.bulks[i]) < 256:
   if self.files[i] is not None:
    buf = self.files[i].read(65536)
    if buf:
     self.bulks[i] += buf
    else:
     self.files[i].close()
     self.files[i] = None
  end_line = self.bulks[i].find('\n')
  if end_line == -1:
   end_line = len(self.bulks[i])
  element = self.bulks[i][:end_line]
  self.bulks[i] = self.bulks[i][end_line+1:]
  return element
 def poppush_uniq(self):
  while True:
   element = self.poppush()
   if element is None:
    return None
   if element != self.pre_element:
    self.pre_element = element
    return element
 def poppush(self):
  try:
   element, index = heappop(self.heap)
  except IndexError:
   return None
  new_element = self.get_next_element_buffered(index)
  if new_element:
   heappush(self.heap, (new_element, index))
  return element
def heappoppush(dir, queue, idx = 0, count = 1):
 heap = file_heap(dir, idx, count)
 while True:
  d = heap.poppush_uniq()
  queue.put(d)
  if d is None: return
def heappoppush2(dir, queue, count = 1):
 heap = []
 procs = []
 queues = []
 pre_element = None
 for i in range(count):
  q = Queue(1024)
  q_buf = queue_buffer(q)
  queues.append(q_buf)
  p = Process(target=heappoppush, args=(dir, q_buf, i, count))
  procs.append(p)
  p.start()
 queues = tuple(queues)
 for i in range(count):
  heappush(heap, (queues[i].get(), i))
 while True:
  try:
   d, i= heappop(heap)
  except IndexError:
   queue.put(None)
   for p in procs:
    p.join()
   return
  else:
   if d is not None:
    heappush(heap,(queues[i].get(), i))
    if d != pre_element:
     pre_element = d
     queue.put(d)
def merge_file(dir):
 heap = file_heap( dir )
 os.system('rm -f '+dir+'.merge')
 fmerge = open(dir+'.merge', 'a')
 element = heap.poppush_uniq()
 fmerge.write(element+'\n')
 while element is not None:
  element = heap.poppush_uniq()
  fmerge.write(element+'\n')
class queue_buffer:
 def __init__(self, queue):
  self.q = queue
  self.rbuf = []
  self.wbuf = []
 def get(self):
  if len(self.rbuf) == 0:
   self.rbuf = self.q.get()
  r = self.rbuf[0]
  del self.rbuf[0]
  return r
 def put(self, d):
  self.wbuf.append(d)
  if d is None or len(self.wbuf) > 1024:
   self.q.put(self.wbuf)
   self.wbuf = []
def diff_file(file_old, file_new, file_diff, buf = 268435456):
 print 'buffer size', buf
 from file_split import split_sort_file
 os.system('rm -rf '+ os.path.splitext(file_old)[0] )
 os.system('rm -rf '+ os.path.splitext(file_new)[0] )
 t = datetime.now()
 split_sort_file(file_old,5,buf)
 split_sort_file(file_new,5,buf)
 print 'split elasped ', datetime.now() - t
 os.system('cat %s/* | wc -l'%os.path.splitext(file_old)[0])
 os.system('cat %s/* | wc -l'%os.path.splitext(file_new)[0])
 os.system('rm -f '+file_diff)
 t = datetime.now()
 zdiff = open(file_diff, 'a')
 old_q = Queue(1024)
 new_q = Queue(1024)
 old_queue = queue_buffer(old_q)
 new_queue = queue_buffer(new_q)
 h1 = Process(target=heappoppush2, args=(os.path.splitext(file_old)[0], old_queue, 3))
 h2 = Process(target=heappoppush2, args=(os.path.splitext(file_new)[0], new_queue, 3))
 h1.start(), h2.start()
 old = old_queue.get()
 new = new_queue.get()
 old_count, new_count = 0, 0
 while old is not None or new is not None:
  if old > new or old is None:
   zdiff.write('< '+new+'\n')
   new = new_queue.get()
   new_count +=1
  elif old < new or new is None:
   zdiff.write('> '+old+'\n')
   old = old_queue.get()
   old_count +=1
  else:
   old = old_queue.get()
   new = new_queue.get()
 print 'new_count:', new_count
 print 'old_count:', old_count
 print 'diff elasped ', datetime.now() - t
 h1.join(), h2.join()

到此这篇关于python文件排序的方法总结的文章就介绍到这了,更多相关python文件排序都有哪些方法内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
玩转python selenium鼠标键盘操作(ActionChains)
Apr 12 Python
浅析Python中MySQLdb的事务处理功能
Sep 21 Python
Python 使用PIL numpy 实现拼接图片的示例
May 08 Python
python selenium自动上传有赞单号的操作方法
Jul 05 Python
Python GUI编程 文本弹窗的实例
Jun 11 Python
Mac在python3环境下安装virtualwrapper遇到的问题及解决方法
Jul 09 Python
python实现各种插值法(数值分析)
Jul 30 Python
Windows下实现将Pascal VOC转化为TFRecords
Feb 17 Python
pytorch 实现在一个优化器中设置多个网络参数的例子
Feb 20 Python
Python第三方库的几种安装方式(小结)
Apr 03 Python
如何利用Python识别图片中的文字
May 31 Python
python 自动刷新网页的两种方法
Apr 20 Python
python识别验证码的思路及解决方案
Sep 13 #Python
Python实现敏感词过滤的4种方法
Sep 12 #Python
Python CategoricalDtype自定义排序实现原理解析
Sep 11 #Python
python 如何利用argparse解析命令行参数
Sep 11 #Python
Python Pivot table透视表使用方法解析
Sep 11 #Python
Python extract及contains方法代码实例
Sep 11 #Python
python 利用zmail库发送邮件
Sep 11 #Python
You might like
MySQL数据源表结构图示
2008/06/05 PHP
php5.2 Json不能正确处理中文、GB编码的解决方法
2014/03/28 PHP
PHP的数组中提高元素查找与元素去重的效率的技巧解析
2016/03/03 PHP
PHP入门教程之数学运算技巧总结
2016/09/11 PHP
php设计模式之单例模式用法经典示例分析
2019/09/20 PHP
分别用marquee和div+js实现首尾相连循环滚动效果,仅3行代码
2011/09/21 Javascript
jQuery源码分析-04 选择器-Sizzle-工作原理分析
2011/11/14 Javascript
javascript定时变换图片实例代码
2013/03/17 Javascript
js 为label标签和div标签赋值的方法
2013/08/08 Javascript
使用 Node.js 做 Function Test实现方法
2013/10/25 Javascript
Jquery响应回车键直接提交表单操作代码
2014/07/25 Javascript
javascript使用for循环批量注册的事件不能正确获取索引值的解决方法
2014/12/20 Javascript
快速使用Bootstrap搭建传送带
2016/05/06 Javascript
javascript replace()第二个参数为函数时的参数用法
2016/12/26 Javascript
使用BootStrap实现表格隔行变色及hover变色并在需要时出现滚动条
2017/01/04 Javascript
微信小程序商品到详情的实现
2017/06/27 Javascript
webpack构建换肤功能的思路详解
2017/11/27 Javascript
vue中的模态对话框组件实现过程
2018/05/01 Javascript
vue-cli3全面配置详解
2018/11/14 Javascript
react的滑动图片验证码组件的示例代码
2019/02/27 Javascript
vue实现密码显示与隐藏按钮的自定义组件功能
2019/04/23 Javascript
JS实现水平遍历和嵌套递归操作示例
2019/08/15 Javascript
如何在vue中使用kindeditor富文本编辑器
2020/12/19 Vue.js
[01:09]DOTA2次级职业联赛 - 99战队宣传片
2014/12/01 DOTA
详细介绍Python函数中的默认参数
2015/03/30 Python
Python如何实现MySQL实例初始化详解
2017/11/06 Python
python简单图片操作:打开\显示\保存图像方法介绍
2017/11/23 Python
Python对ElasticSearch获取数据及操作
2019/04/24 Python
django mysql数据库及图片上传接口详解
2019/07/18 Python
Anaconda之conda常用命令介绍(安装、更新、删除)
2019/10/06 Python
2020版Python学习路线图(附学习资料)
2020/09/15 Python
Python中的流程控制详解
2021/02/18 Python
物业品质提升方案
2014/06/08 职场文书
孔繁森观后感
2015/06/10 职场文书
画错魏国疆域啦!《派对咖孔明》动画因作画失误于官网致歉
2022/04/07 日漫
vue3 自定义图片放大器效果的示例代码
2022/07/23 Vue.js