[Python]生成 txt 文件

前段时间有位客户问: 你们的程序能不能给我们生成个 txt 文件,把新增的员工都放进来,字段也不需要太多,就要 员工姓名/卡号/员工编号/员工职位/公司 这些字段就行了,然后我们的程序会去读取这个 txt 文件,拿里面的内容,读完之后会这个文件删掉
我: 可以接受延迟吗?可能没办法实时生成,写个脚本,用定时任务去跑还是可以实现的
客户: 可以呀,那个脚本 30mins 跑一次就行
这篇文章就记录一下大概实现思路,后续如果遇到类似需求,就可以直接 copy 代码了

实现思路:

  • 定义全局变量 update_time
  • 判断 update_time 是否为空
    • 为空,说明是第一次查询数据,取查到的最后一条记录的 create_time ,赋值给 update_time
    • 不为空,说明不是第一次查询数据,查询数据时, create_time > update_time ,同时更新 update_time
  • 判断 txt 文件是否存在
    • 存在,则 txt 表头不需要重新生成
    • 不存在, txt 表头需要重新生成

其实逻辑很简单, Python 类库也很丰富,接下来就上代码:

import pymysql
import os
import argparse
import schedule
import datetime

update_time = ""

def handle_variables(server_ip,password):
    global real_ip 
    real_ip = server_ip
    global root_password 
    root_password = password

def get_person_info():
    connection = pymysql.connect(host = real_ip,
                             user = 'root',
                             password = root_password,
                             db = 'xxx'
                             )

    try:
        global update_time
        cur = connection.cursor()
        if "" == update_time :
            sql = "select `name`,`card_num`,`code`,`postion`,`company_id`,`gmt_create` from person"
        else :
            sql = "select `name`,`card_num`,`code`,`postion`,`company_id`,`gmt_create` from person where `gmt_create` > '" + update_time + "'"
        cur.execute(sql)
        query_person_info_list = cur.fetchall()
        
        # get the time of the last record
        if len(query_person_info_list) != 0:
            temp_list = query_person_info_list[-1]
            update_time = temp_list[-1]
            if isinstance(update_time, datetime.datetime):
                update_time = update_time.strftime('%Y-%m-</
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值