我正在尝试用 python 创建一个 log_file.txt 。 所以,每当我每次运行脚本时,它都应该生成新的日志文件。
例如:
日志文件 日志文件1 日志文件2 。 。 。 .
def log(message):
try:
counter = 1
# Format the log message with current date and time
log_message = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {message}\n"
# Write the message to the log file
with open("log_file.txt", "a") as log_file:
log_file.write(log_message)
except Exception as e:
print(f"Error occurred while logging: {e}")
这是我尝试过的。
import os
from datetime import datetime
def log(message):
try:
counter = 1
while os.path.exists(f"log_file{counter}.txt"):
counter += 1
log_message = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {message}\n"
with open(f"log_file{counter}.txt", "a") as log_file:
log_file.write(log_message)
except Exception as e:
print(f"Error occurred while logging: {e}")
log("This is a log message.")
请尝试这个