python创建和维护每日文本文件,记录并防止给定数据列表中项目的重复
import os
from datetime import date
def write_to_today_txt(item):
today = date.today()
path = r'F:\log'
if not os.path.exists(path):
os.makedirs(path)
today_txt_path = os.path.join(path, f"报表导出{today}.txt")
# 检查今天的txt文件是否已经存在,如果存在则读取已经写入的数据
existing_data = set()
if os.path.isfile(today_txt_path):
with open(today_txt_path, "r") as file:
existing_data = set(file.read().splitlines())
if item not in existing_data:
with open(today_txt_path, "a") as file:
file.write(item + "\n")
existing_data.add(item)
return False
else:
print(item,"已完成,无需再执行")
return True
# 例如:数据列表
data_list = ['a', 'b', 'c']
# 调用函数
for item in data_list:
write_to_today_txt(item)
本文作者: 永生
本文链接: https://yys.zone/detail/?id=313
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!
评论列表 (0 条评论)