This repository has been archived on 2024-09-30. You can view files and clone it, but cannot push or open issues/pull-requests.
adbMonitor/modules/fileRW.py

64 lines
2.0 KiB
Python

import json
import logging
import os
def read_last_n_lines(n):
file_path = './cache/record.txt'
try:
with open(file_path, 'r') as file:
lines = file.readlines()
last_n_lines = [line.rstrip() for line in lines[-n:]]
logging.info(f"read_last_n_lines:last_{n}_lines={last_n_lines} ")
return last_n_lines
except FileNotFoundError:
logging.error(f"read_last_n_lines error: 文件未找到或路径错误。")
print("文件未找到或路径错误。")
return None
def generate_json_data(lines):
# 生成包含时间信息的 JSON 数据
data = {
'time': {}
}
for i, line in enumerate(lines, 1):
data['time'][str(i)] = line
json_data = json.dumps(data)
return json_data
def delete_file(file_path):
try:
# 检查文件是否存在
if os.path.exists(file_path):
# 确保文件已关闭
with open(file_path, "a"):
pass
# 删除文件
os.remove(file_path)
logging.info(f"文件 {file_path} 已成功删除!")
print(f"文件 {file_path} 已成功删除!")
else:
logging.info(f"文件 {file_path} 不存在,无法删除!")
print(f"文件 {file_path} 不存在,无法删除!")
except Exception as e:
logging.error(f"delete_file error: {e}")
print(f"删除文件时出现错误:{e}")
def write_error_devices(text, newline=True):
filename = "./error_devices.txt"
# 判断当前目录下是否有txt文件
if not os.path.exists(filename):
# 如果文件不存在,则新建并写入文本
with open(filename, "w") as file:
file.write(text)
else:
# 如果文件已存在,则在文件末尾追加文本,并换行(如果需要)
with open(filename, "a") as file:
if newline:
file.write("\n" + text)
else:
file.write(text)