根据当前日期打开.txt文件(python)

问题描述 投票:0回答:1

我正在构建一个 Python 脚本,该脚本读取

.txt
文件的最后一行,并将其发送到
SQL
服务器数据库以进行后期数据管理。我有一台数控机床,将生产过程中的实时数据存储在
.txt
文件中。
.txt
文件的默认名称是“industry_YYYY-MM-DD”。每天都会创建一个新的
.txt
文件及其日期。我想每天早上运行我的脚本,并让它在后台运行,每 5 秒将数据发送到
sql
数据库。此外,我希望脚本仅打开具有相应日期的
.txt
文件并从中检索数据。

目前脚本看起来像这样:

import time

import pyodbc

# Replace these values with your actual database connection details
server = r'****'
database = '****'
username = '****'
password = '****'
table_name = 'python2'  # Replace with your actual table name

connection_string = f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'

file_path = r'C:\Users\LEOPARD\Desktop\EU\Unidades Curriculares\5ª matrícula\DPE\Punc TECHNOLOGY\Relatórios Diários\06-01-2023.txt'
previous_line = ""

while True:
    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()

            if lines:
                last_line = lines[-1].strip()

                # Check if the last line is different from the previous line
                if last_line != previous_line:
                    # Update the previous line
                    previous_line = last_line

                    # Check if the last line contains the substring "--"
                    if "--" in last_line:
                        print(f"New last line of the file: {last_line}")
 
                        # Connect to the SQL Server database
                        connection = pyodbc.connect(connection_string)
                        cursor = connection.cursor()

                        # Insert the last line into the specified table
                        insert_query = f"INSERT INTO {table_name} (linha) VALUES (?)"
                        values = (last_line,)
                        cursor.execute(insert_query, values)
                        connection.commit()

                        # Close the database connection
                        connection.close()
                    else:
                        print("Waiting for the next line")
                else:
                    print("Same line")
            else:
                print("The file is empty.")
    except FileNotFoundError:
        print(f"File not found: {file_path}")
    except Exception as e:
        print(f"An error occurred: {e}")

    # Wait for 5 seconds before the next iteration
    time.sleep(5)
   #Ctrl + C to interrupt script

如果我手动将目录更改为我想要打开的

.txt
,则脚本正在工作,但我希望它自动打开与日期相对应的
.txt

这是每日报告的示例:

he is an example of the daily reports

python sql-server
1个回答
0
投票

Python 确实有标准的 datetime 模块,您可以使用它来获取 todays 日期,只需将其转换为字符串并将其添加到您的路径或文件名中即可。

import datetime
import zoneinfo
from pathlib import Path

my_file_path = Path(
    "C:/Users/LEOPARD/Desktop/EU/Unidades Curriculares/5ª matrícula/DPE/Punc TECHNOLOGY/Relatórios Diários"
)

todays_dt = datetime.datetime.now(tz=zoneinfo.ZoneInfo("America/Santiago"))
todays_str = todays_dt.strftime("%Y-%m-%d")  # '2024-01-07'
print(my_file_path.joinpath(f"industry_{todays_str}.txt")) # 'C:/Users/LEOPARD/Desktop/EU/Unidades Curriculares/5ª matrícula/DPE/Punc TECHNOLOGY/Relatórios Diários/industry_2024-01-07.txt'
© www.soinside.com 2019 - 2024. All rights reserved.