zoukankan      html  css  js  c++  java
  • python中yield迭代器

     excel数据有上千条,最好不要一次性全部读出来放在列表会消耗内存,需要每读一条用yield返回一条;当运行到yield '';的时候,程序暂停了,不会往下继续执行,
     
    class SDMS(object):

    def cpyExcel(self, path):
    if os.path.isfile(path):
    print("%s文件存在" % path)
    else:
    print("%s文件不存在" % path)
    return

    def readExcel(path):
    xls = rpa.excel.open(path)
    sheet = xls.get_sheet()
    col_num = int(sheet.col_count())
    for i in range(1, col_num + 1):
    col_letter = get_column_letter(i)
    print(sheet.read(col_letter))
    yield (sheet.read(col_letter)) #迭代器
    xls.close()

    return readExcel(path)


    def writeCpyExcel(self, path, data_it):
    col_num = 1
    col_letter = get_column_letter(col_num)
    xls = rpa.excel.create()
    sheet = xls.get_sheet()
    while True:
    try:
    sheet.write(col_letter, next(data_it))
    col_num += 1
    col_letter = get_column_letter(col_num)
    except:
    print("except, 数据读取完成。")
    break
    xls.save(file=path)
    xls.close()

    def start():
    sdms = SDMS()
    sync_filename = time.strftime("%Y%m%d_%H%M%S", time.localtime()) + "同步数据.xlsx"
    sync_filepath = os.path.join(logdir, sync_filename)
    data_it = sdms.cpyExcel(self.filepath) #读取excel返回迭代器data_it,因为原本的excel无法编辑,所以要复制出来编辑
    sdms.writeCpyExcel(sync_filepath, data_it) #通过迭代器data_it,再写入另外一个excel

  • 相关阅读:
    toPrimitive方法使用
    使用js导入Excel数据,转化为json,导出指定json,合并单元格为excel
    vue-router基本使用
    json另类使用
    z-index无效情况
    构造函数另类使用。
    在worker中使用offscreenCanvas
    使用git提交代码一条龙
    IntelliJ IDEA使用技巧一览表
    Android studio 常用快捷键
  • 原文地址:https://www.cnblogs.com/harryTree/p/11375737.html
Copyright © 2011-2022 走看看