zoukankan      html  css  js  c++  java
  • 使用yield处理文件

    写文件

    # -*- coding:utf-8 -*-
    import random
    import threading
    import string
    import time
    t1 = time.time()
    def write(x):
        with open('a.txt','a+')as a:
            a.write(x + '||')
    
    def run():
        for x in range(10000000):
            strs = str(random.randint(1000,2000)) +random.choice(string.ascii_letters)*10
            write(strs)
    for x in range(10):
        t = threading.Thread(target=run)
        t.start()
    t2 = time.time()
    print(t2 - t1)
    

    读文件

    # -*- coding:utf-8 -*-
    def readbooks(f, newline):
        # f为传入的文件名,newline为分隔符
        buf = ""
        # 缓存,处理已经读出来的数据量
        while 1:
            while newline in buf:
                # 缓存中的数据是否存在分隔符
                pos = buf.index(newline)
                # 如果存在就找到字符的位置,比如0或者1或者2
                yield buf[:pos]
                # 暂停函数,返回缓存中的从头到字符的位置
                buf = buf[pos + len(newline):]
                # 缓存变成了,字符的位置到末尾
            chunk = f.read(2010 * 10)
            # 读取2010*10的字符
            if not chunk:
                # 已经读取到了文件结尾
                yield buf
                break
            buf += chunk
            # 加到缓存
     with open('a.txt','r')as f:
         for line in readbooks(f,'||'):
             print(line)
    
  • 相关阅读:
    zyUpload+struct2完成文件上传
    js表单动态添加数据并提交
    Hibernate注解
    ueditor的配置和使用
    设计模式
    静态Include和动态Include测试并总结
    java笔试题
    perf使用示例1
    perf 简介
    ss简单使用
  • 原文地址:https://www.cnblogs.com/xidongyu/p/11630329.html
Copyright © 2011-2022 走看看