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

猜你喜欢

转载自www.cnblogs.com/harryTree/p/11375737.html