[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-%d %H:%M:%S')
        
        # if the txt not exists, add new text
        if not os.path.exists('add_person.txt') :
            with open('add_person.txt', 'w') as f:
                f.write('Lastname, Firstname, CardNumber, Employee ID, Designation, Department \n')
                for person_info in query_person_info_list :
                    person_name = person_info[0]
                    # the name is generally first + last, which needs to be converted
                    person_name_list = person_name.split()
                    person_first_name = person_name_list[0]
                    start_length = len(person_first_name) + 1
                    person_last_name = person_name[start_length:]
                    f.write(str(person_last_name) + ', ' + str(person_first_name) + ', ')
                    
                    card_number = person_info[1]
                    employee_id = person_info[2]
                    designation = person_info[3]
                    department = person_info[4]
                    
                    if card_number is not None :
                        f.write(str(card_number) + ', ')
                    else :
                        f.write(', ')
                        
                    if employee_id is not None :
                        f.write(str(employee_id) + ', ')
                    else :
                        f.write(', ')
                    
                    if designation is not None :
                        f.write(str(designation) + ', ')
                    else :
                        f.write(', ')
                        
                    if department is not None :
                        # get department name
                        department_sql = "select `name` from zone where id = " + str(department)
                        cur.execute(department_sql)
                        department_result = cur.fetchone()
                        department_name = department_result[0]
                        f.write(str(department_name))
                    else :
                        f.write(', ')
                    
                    f.write('\n')
        # if the txt exists, update the text
        else :
            # get original data
            with open('add_person.txt', 'r') as e:
                data = e.readlines()
            
            with open('add_person.txt', 'w') as f:
                # first save the original data 
                for write_data in data :
                    f.write(write_data)
                # then save new data
                for person_info in query_person_info_list :
                    person_name = person_info[0]
                    # the name is generally first + last, which needs to be converted
                    person_name_list = person_name.split()
                    person_first_name = person_name_list[0]
                    start_length = len(person_first_name) + 1
                    person_last_name = person_name[start_length:]
                    f.write(str(person_last_name) + ', ' + str(person_first_name) + ', ')
                    
                    card_number = person_info[1]
                    employee_id = person_info[2]
                    designation = person_info[3]
                    department = person_info[4]
                    
                    if card_number is not None :
                        f.write(str(card_number) + ', ')
                    else :
                        f.write(', ')
                        
                    if employee_id is not None :
                        f.write(str(employee_id) + ', ')
                    else :
                        f.write(', ')
                    
                    if designation is not None :
                        f.write(str(designation) + ', ')
                    else :
                        f.write(', ')
                        
                    if department is not None :
                        # get department name
                        department_sql = "select `name` from zone where id = " + str(department)
                        cur.execute(department_sql)
                        department_result = cur.fetchone()
                        department_name = department_result[0]
                        f.write(str(department_name))
                    else :
                        f.write(', ')
                    
                    f.write('\n')
                        
    except IOError:
        print('Error: get update person info fail')
    finally:
        cur.close()
        connection.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="please enter")
    parser.add_argument("--server_ip", "-server", help="server ip", default="", type=str, required=False)
    parser.add_argument("--password", "-p", help="devops infra password", default="", type=str, required=False)
    
    args = parser.parse_args()
  
    # let the variable become a global variable, no need to pass it
    handle_variables(args.server_ip, args.password)
  
    # execute the method every 30mins
    #schedule.every(30).minutes.do(get_person_info)
    
    # for test -- execute the method every 30 seconds
    schedule.every(30).seconds.do(get_person_info)

    while True:
        # run task 
        schedule.run_pending()   

以上~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/15353.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【VM服务管家】VM4.0平台SDK_2.3 控件嵌入类

目录 2.3.1 渲染结果:通过绑定流程或模块获取渲染结果的方法2.3.2 渲染控件:渲染控件加载本地图像的方法2.3.3 渲染控件:渲染控件上自定义图形的方法2.3.4 参数控件:参数配置控件绑定模块的方法2.3.5 控件颜色:控件颜色…

Java新提案,最终还是靠近C#了

Java是一门非常优秀的编程语言,特别是生态繁荣,成熟的轮子很多,各种解决方案都有,要开发一个项目,只需把轮子组装,并根据自己的项目,进行自定义修改,可以极大地提升开发效率。 曾经…

【算法】【算法杂谈】判断点是否在三角形内部(面积法和向量法)

目录 前言问题介绍解决方案代码编写java语言版本c语言版本c语言版本 思考感悟写在最后 前言 当前所有算法都使用测试用例运行过,但是不保证100%的测试用例,如果存在问题务必联系批评指正~ 在此感谢左大神让我对算法有了新的感悟认识! 问题介…

react-antd-procomponents组件库 ProTable表格实现跨页多选。

table表格多选时所需要的api 1.onSelect - 单行选择(用户手动选择/取消选择某行的回调) 2.onSelectMultiple - 多行选择(用户使用键盘 shift 选择多行的回调) 3.onSelectAll - 全选全不选(用户手动选择/取消选择所有行的回调) 4.onChange - 每次选择行都…

Page管理机制

Page页分类 Buffer Pool 的底层采用链表数据结构管理Page。在InnoDB访问表记录和索引时会在Page页中缓存,以后使用可以减少磁盘IO操作,提升效率 Page根据状态可以分为三种类型: - free page : 空闲page,未被使用 - …

耐腐蚀高速电动针阀在半导体硅片清洗机化学药液流量控制中的应用

摘要:化学药液流量的精密控制是半导体湿法清洗工艺中的一项关键技术,流量控制要求所用调节针阀一是开度电动可调、二是具有不同的口径型号、三是高的响应速度,四是具有很好的耐腐蚀性,这些都是目前提升半导体清洗设备性能需要解决…

2023/4/25总结

刷题&#xff1a; 第一周任务 - Virtual Judge (vjudge.net) 1.这一题的思路就是先排除前面和后面相等的&#xff0c;然后找到不等的情况&#xff0c;不等情况的下标开始前后都走&#xff0c;看看是不是和b数组构成了一个升序数组即可。 #include<stdio.h> #define Ma…

【数据结构】链表详解

本片要分享的内容是链表&#xff0c;为方便阅读以下为本片目录 目录 1.顺序表的问题及思考 1.链表的遍历 2.头部插入 2.1开辟空间函数分装 3.尾部插入 纠正 4.尾部删除 5.头部删除 6.数据查找 7.任意位置插入 1.顺序表的问题及思考 上一篇中讲解了顺序表中增删查…

从源码全面解析LinkedBlockingQueue的来龙去脉

一、引言 并发编程在互联网技术使用如此广泛&#xff0c;几乎所有的后端技术面试官都要在并发编程的使用和原理方面对小伙伴们进行 360 的刁难。 二、使用 对于阻塞队列&#xff0c;想必大家应该都不陌生&#xff0c;我们这里简单的介绍一下&#xff0c;对于 Java 里面的阻塞…

Python | 基于LendingClub数据的分类预测研究Part01——问题重述+特征选择+算法对比

欢迎交流学习~~ 专栏&#xff1a; 机器学习&深度学习 本文利用Python对数据集进行数据分析&#xff0c;并用多种机器学习算法进行分类预测。 具体文章和数据集可以见我所发布的资源&#xff1a;发布的资源 Python | 基于LendingClub数据的分类预测研究Part01——问题重述特…

在.NET Core中正确使用HttpClient的方式

HttpClient 是 .NET Framework、.NET Core 或 .NET 5以上版本中的一个类&#xff0c;用于向 Web API 发送 HTTP 请求并接收响应。它提供了一些简单易用的方法&#xff0c;如 GET、POST、PUT 和 DELETE&#xff0c;可以很容易地构造和发送 HTTP 请求&#xff0c;并处理响应数据。…

【Excel统计分析插件】上海道宁为您提供统计分析、数据可视化和建模软件——Analyse-it

Analyse-it是Microsoft Excel中的 统计分析插件 它为Microsoft Excel带来了 易于使用的统计软件 Analyse-it在软件中 引入了一些新的创新统计分析 Analyse-it与 许多Excel加载项开发人员不同 使用完善的软件开发和QA实践 包括单元/集成/系统测试 敏捷开发、代码审查 …

虹科案例|虹科Micronor光纤传感器,实现核磁共振新应用!

PART 1 背景介绍 光纤传感器已成为推动MRI最新功能套件升级和新MRI设备设计背后的关键技术。将患者的某些活动与MRI成像系统同步是越来越受重视的需求。磁场强度随着每一代的发展而增大&#xff0c;因此&#xff0c;组件的电磁透明度在每一代和新应用中变得更加重要。 光学传…

《Netty》从零开始学netty源码(四十六)之PooledByteBuf

PooledByteBuf Netty中一大块内存块PoolChunk默认大小为4MB&#xff0c;为了尽可能充分利用内存会将它切成很多块PooledByteBuf&#xff0c;PooledByteBuf的类关系图如下&#xff1a; PooledUnsafeDirectByteBuf与PooledUnsafeHeapByteBuf直接暴露对象的底层地址。 PooledByt…

【英语】100个句子记完7000个托福单词

其实主要的7000词其实是在主题归纳里面&#xff0c;不过过一遍100个句子也挺好的&#xff0c;反正也不多。 文章目录 Sentence 01Sentence 02Sentence 03Sentence 04Sentence 05Sentence 06Sentence 07Sentence 08Sentence 09Sentence 10Sentence 11Sentence 12Sentence 13Sent…

数据分析中常见标准的参考文献

做数据分析过程中&#xff0c;有些分析法方法的标准随便一搜就能找到&#xff0c;不管是口口相传还是默认&#xff0c;大家都按那样的标准做了。日常分析不细究出处还可以&#xff0c;但是正式的学术论文你需要为你写下的每一句话负责&#xff0c;每一个判断标准都应该有参考文…

Docker | 解决docker 容器中csv文件乱码的情况

问题描述&#xff1a;在Ubuntu docker容器中&#xff0c;打开.csv文件时显示乱码 问题如图 错误分析&#xff1a; 用locale查看所用容器支持的字符集 从输出可以看到&#xff0c;系统使用的是POSIX字符集&#xff0c;POSIX字符集是不支持中韩文的&#xff0c;而UTF-8是支持中…

刷题4.28

1、 开闭原则软件实体&#xff08;模块&#xff0c;类&#xff0c;方法等&#xff09;应该对扩展开放&#xff0c;对修改关闭&#xff0c;即在设计一个软件系统模块&#xff08;类&#xff0c;方法&#xff09;的时候&#xff0c;应该可以在不修改原有的模块&#xff08;修改关…

vue之--使用TypeScript

搭配 TypeScript 使用 Vue​ 像 TypeScript 这样的类型系统可以在编译时通过静态分析检测出很多常见错误。这减少了生产环境中的运行时错误&#xff0c;也让我们在重构大型项目的时候更有信心。通过 IDE 中基于类型的自动补全&#xff0c;TypeScript 还改善了开发体验和效率。…

【Android Framework (八) 】- Service

文章目录 知识回顾启动第一个流程initZygote的流程system_serverServiceManagerBinderLauncher的启动AMS 前言源码分析1.startService2.bindService 拓展知识1:Service的两种启动方式对Service生命周期有什么影响&#xff1f;2:Service的启动流程3:Service的onStartCommand返回…