第一次写python的小程序

功能:遍历目录下的所有txt文件将*和-之间的时间戳转换为rtc时间

# -*- coding: UTF-8 -*-

import sys
import re
import os
import shutil
import argparse
import datetime
import chardet

def get_encoding(file):
    with open(file, 'rb') as f:
      data = f.read()
      return chardet.detect(data)['encoding']

def main():
    path = os.path.abspath("./")
    path_rtctime = os.path.join(path, "rtctime_log")
    if os.path.exists(path_rtctime):
        shutil.rmtree(path_rtctime)
    os.mkdir(path_rtctime)
    files = os.listdir(path)
    for file in files:
        src = os.path.join(path, file)
        if os.path.isfile(src) and src.split('.')[-1].lower() == 'txt':
            dst = os.path.join(path_rtctime, file)
            with open(dst, 'a', encoding='utf-8') as f_write:
                f_write.truncate(0)
                encoding_format = get_encoding(src)
                with open(src, 'r', encoding=encoding_format) as f_read:
                    line = f_read.readline()
                    while line:
                        match = re.findall(r'(?<=\*).+?(?=\-)', line)
                        if match:
                            temp = match[0]
                            if temp.isdigit() and len(temp)==14:
                                rtctime = str(datetime.datetime.fromtimestamp(int(temp[1:11]))) + '.' + temp[11:]
                                #print(line.replace(temp, rtctime))
                                f_write.write(line.replace(temp, rtctime))
                            else:
                                f_write.write(line)
                        else:
                            f_write.write(line)
                        line = f_read.readline()
            
if __name__ == "__main__":
     sys.exit(main()) 

python脚本生成exe可执行程序:

安装pyinstaller:pip install pyinstaller

由于找不到pyinstaller命令,所以执行下面的命令来使用pyinstaller

pip show pyinstaller,来查找安装目录。

cd 进入到查找到的目录的PyInstaller目录。

生成exe:python __main__.py -F test.py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值