Python多进程读取文件操作方法详解,,python读取文件的操
Python多进程读取文件操作方法详解,,python读取文件的操
python读取文件的操作方法很便捷实用,本文的python源码利用Python多进程读取文件操作方法,是为读取超大的文本文件而编写的。代码中使用多了进程分块读取方式,将每一块单独输出成文件使用。
学习使用python都是为了在工作上能所帮助和提升自己的业务水平。多进程是很好的一种方法。
在python基础部分有讲到过Python open()函数文件打开、读、写操作,虽然都是对文件的操作,但意义完全不同。
Python多进程读取文件操作方法源码如下:(仅供参考,如需使用请适当修改)
# -*- coding: GBK -*-import urlparseimport datetimeimport osfrom multiprocessing import Process,Queue,Array,RLockWORKERS = 4BLOCKSIZE = 100000000FILE_SIZE = 0def getFilesize(file): """ 获取要读取文件的大小 """ global FILE_SIZE fstream = open(file,'r') fstream.seek(0,os.SEEK_END) FILE_SIZE = fstream.tell() fstream.close()def process_found(pid,array,file,rlock): global FILE_SIZE global JOB global PREFIX """ 进程处理 Args: pid:进程编号 array:进程间共享队列,用于标记各进程所读的文件块结束位置 file:所读文件名称 各个进程先从array中获取当前最大的值为起始位置startpossition 结束的位置 endpossition (startpossition+BLOCKSIZE) if (startpossition+BLOCKSIZE) <FILE_SIZE else FILE_SIZE if startpossition==FILE_SIZE则进程结束 if startpossition==0则从0开始读取 if startpossition!=0 为防止行被block截断的情况,先读一行不处理,从下一行开始正式处理 if 当前位置 <=endpossition 就readline 否则越过边界,就从新查找array中的最大值 """ fstream = open(file,'r') while True: rlock.acquire() print 'pid%s'%pid,','.join([str(v) for v in array]) startpossition = max(array) endpossition = array[pid] = (startpossition+BLOCKSIZE) if (startpossition+BLOCKSIZE)<FILE_SIZE else FILE_SIZE rlock.release() if startpossition == FILE_SIZE:#end of the file print 'pid%s end'%(pid) break elif startpossition !=0: fstream.seek(startpossition) fstream.readline() pos = ss = fstream.tell() ostream = open('/data/download/tmp_pid'+str(pid)+'_jobs'+str(endpossition),'w') while pos<endpossition: #处理line www.iplaypy.com line = fstream.readline() ostream.write(line) pos = fstream.tell() print 'pid:%s,startposition:%s,endposition:%s,pos:%s'%(pid,ss,pos,pos) ostream.flush() ostream.close() ee = fstream.tell() fstream.close()def main(): global FILE_SIZE print datetime.datetime.now().strftime("%Y/%d/%m %H:%M:%S") file = "/data/pds/download/scmcc_log/tmp_format_2011004.log" getFilesize(file) print FILE_SIZE rlock = RLock() array = Array('l',WORKERS,lock=rlock) threads=[] for i in range(WORKERS): p=Process(target=process_found, args=[i,array,file,rlock]) threads.append(p) for i in range(WORKERS): threads[i].start() for i in range(WORKERS): threads[i].join() print datetime.datetime.now().strftime("%Y/%d/%m %H:%M:%S") if __name__ == '__main__': main()
python多进程处理数据之类的操作,是做为一个python专业工程师必会的基本知识。想要做一个好的资深python工程师要了解的内容还有很多。不妨看看北京高薪加期权招资深Python开发工程师,都需要什么样的条件吧。
编橙之家文章,
相关内容
- 用Python代码实现阿拉伯数字与罗马数字转换讲解,pyt
- Linux环境下的Python翻译工具源码,linuxpython,编橙之家P
- Python实时监控Linux cpu使用率实现方法,pythonlinux,Python监
- 用python遍历方法统计linux内核文件的行数示例,,用pyt
- python statvfs方法获知磁盘的空间量,pythonstatvfs,python s
- python监控用户登陆并发送通知邮件方法,python用户登陆
- Python迅雷快车旋风地址加密解密,python加密解密,Pytho
- Windows环境用Python备份MySQL脚本,python备份mysql脚本,Win
- Python批量删除windows下svn文件夹的方法,pythonsvn,本文为
- 使用Python xlrd模块读取Excel格式文件的方法,pythonxlrd,这
评论关闭