文件监视器循环无法在重新运行代码时继续上次的位置。

huangapple go评论77阅读模式
英文:

File watcher loop cannot continue where it left off when re-running the code

问题

以下是代码的翻译部分:

import os
import glob
import json
import pandas as pd
import time
from datetime import datetime
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows

def jsonFilesInDirectory(my_dir: str):
    # 获取目录中的 JSON 文件列表
    json_files = glob.glob(os.path.join(my_dir, "*.json"))
    return json_files

def clean_value(value):
    # 清理数字值,去除不必要的字符
    return float(value.replace('\xa0s', '').replace('\xa0ms', '').replace(',', ''))

def doThingsWithNewFiles(fileDiff: list, my_dir: str, workbook):
    for file_name in fileDiff:
        file_path = os.path.join(my_dir, file_name)
        with open(file_path, 'r', encoding='utf-8') as file:
            try:
                json_data = json.load(file)

                # 从 JSON 文件中提取数据
                url = json_data["finalUrl"]
                fetch_time = json_data["fetchTime"]

                audits = json_data["audits"]
                fcp_metric = audits["first-contentful-paint"]["id"]
                fcp_value = audits["first-contentful-paint"]["displayValue"]
                fcp_score = audits["first-contentful-paint"]["score"]
                lcp_metric = audits["largest-contentful-paint"]["id"]
                lcp_value = audits["largest-contentful-paint"]["displayValue"]
                lcp_score = audits["largest-contentful-paint"]["score"]
                fmp_metric = audits["first-meaningful-paint"]["id"]
                fmp_value = audits["first-meaningful-paint"]["displayValue"]
                fmp_score = audits["first-meaningful-paint"]["score"]
                si_metric = audits["speed-index"]["id"]
                si_value = audits["speed-index"]["displayValue"]
                si_score = audits["speed-index"]["score"]
                tbt_metric = audits["total-blocking-time"]["id"]
                tbt_value = audits["total-blocking-time"]["displayValue"]
                tbt_score = audits["total-blocking-time"]["score"]
                cls_metric = audits["cumulative-layout-shift"]["id"]
                cls_value = audits["cumulative-layout-shift"]["displayValue"]
                cls_score = audits["cumulative-layout-shift"]["score"]

                categories = json_data["categories"]
                perf_metric = categories["performance"]["id"]
                perf_value = 0
                perf_score = categories["performance"]["score"]

                # 清理值并格式化获取时间
                cleaned_fcp_value = clean_value(fcp_value)
                cleaned_lcp_value = clean_value(lcp_value)
                cleaned_fmp_value = clean_value(fmp_value)
                cleaned_si_value = clean_value(si_value)
                cleaned_tbt_value = clean_value(tbt_value)
                datetime_obj = datetime.strptime(fetch_time, "%Y-%m-%dT%H:%M:%S.%fZ")
                cleaned_fetch_time = datetime_obj.strftime("%Y-%m-%d %H:%M:%S")

                # 为 DataFrame 创建数据字典
                data_dict = {
                    "fetch_time": [cleaned_fetch_time] * 7,
                    "url": 
* 7,
"metric": ["performance","first_contentful_paint", "largest_contentful_paint", "first-meaningful-paint", "speed-index", "total-blocking-time", "cumulative-layout-shift"], "value": [perf_value, cleaned_fcp_value, cleaned_lcp_value, cleaned_fmp_value, cleaned_si_value, cleaned_tbt_value, cls_value], "score": [perf_score, fcp_score, lcp_score, fmp_score, si_score, tbt_score, cls_score] } df = pd.DataFrame(data_dict) # 将 DataFrame 追加到 Excel 文件 sheet_name = "Sheet1" if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] startrow = sheet.max_row for row in dataframe_to_rows(df, index=False, header=False): sheet.append(row) else: sheet = workbook.create_sheet(sheet_name) for row in dataframe_to_rows(df, index=False, header=True): sheet.append(row) print(f"从文件 {file_name} 中提取数据并追加到 Excel 文件") except KeyError as e: print(f"处理文件 '{file_name}' 时发生 KeyError 错误: {e}") except json.JSONDecodeError as e: print(f"处理文件 '{file_name}' 时发生 JSONDecodeError 错误: {e}") except Exception as e: print(f"处理文件 '{file_name}' 时发生错误: {e}") # 其余部分省略...

如果您需要对其他部分进行翻译,请提供相应的代码段,并告诉我需要翻译的内容。

英文:

I have create this File Watcher Loop, when I run the code, it scans a specific folder for .json files and append to an 'output.xls' file. Then the code continues to run in a loop, scanning new files in the folder, and repeat the process. This works just fine, however, when I stop the code (laptop turn-off, or something), new files are still being added to the folder, and then when I re-run the code, I cannot continue where I left off, I have to delete the output.xls file and start over again.

Is there a way for this to save the history of the files already appended when I stop the code, and continue adding files that have not been appended when I re-run the code?

import os
import glob
import json
import pandas as pd
import time
from datetime import datetime
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
def jsonFilesInDirectory(my_dir: str):
# Get a list of JSON files in the directory
json_files = glob.glob(os.path.join(my_dir, "*.json"))
return json_files
def clean_value(value):
# Clean up numeric values by removing unnecessary characters
return float(value.replace('\xa0s', '').replace('\xa0ms', '').replace(',', ''))
def doThingsWithNewFiles(fileDiff: list, my_dir: str, workbook):
for file_name in fileDiff:
file_path = os.path.join(my_dir, file_name)
with open(file_path, 'r', encoding='utf-8') as file:
try:
json_data = json.load(file)
# Extract data from the JSON file
url = json_data["finalUrl"]
fetch_time = json_data["fetchTime"]
audits = json_data["audits"]
fcp_metric = audits["first-contentful-paint"]["id"]
fcp_value = audits["first-contentful-paint"]["displayValue"]
fcp_score = audits["first-contentful-paint"]["score"]
lcp_metric = audits["largest-contentful-paint"]["id"]
lcp_value = audits["largest-contentful-paint"]["displayValue"]
lcp_score = audits["largest-contentful-paint"]["score"]
fmp_metric = audits["first-meaningful-paint"]["id"]
fmp_value = audits["first-meaningful-paint"]["displayValue"]
fmp_score = audits["first-meaningful-paint"]["score"]
si_metric = audits["speed-index"]["id"]
si_value = audits["speed-index"]["displayValue"]
si_score = audits["speed-index"]["score"]
tbt_metric = audits["total-blocking-time"]["id"]
tbt_value = audits["total-blocking-time"]["displayValue"]
tbt_score = audits["total-blocking-time"]["score"]
cls_metric = audits["cumulative-layout-shift"]["id"]
cls_value = audits["cumulative-layout-shift"]["displayValue"]
cls_score = audits["cumulative-layout-shift"]["score"]
categories = json_data["categories"]
perf_metric = categories["performance"]["id"]
perf_value = 0
perf_score = categories["performance"]["score"]
# Clean up values and format the fetch time
cleaned_fcp_value = clean_value(fcp_value)
cleaned_lcp_value = clean_value(lcp_value)
cleaned_fmp_value = clean_value(fmp_value)
cleaned_si_value = clean_value(si_value)
cleaned_tbt_value = clean_value(tbt_value)
datetime_obj = datetime.strptime(fetch_time, "%Y-%m-%dT%H:%M:%S.%fZ")
cleaned_fetch_time = datetime_obj.strftime("%Y-%m-%d %H:%M:%S")
# Create a data dictionary for the DataFrame
data_dict = {
"fetch_time": [cleaned_fetch_time] * 7,
"url": 
* 7, "metric": ["performance","first_contentful_paint", "largest_contentful_paint", "first-meaningful-paint", "speed-index", "total-blocking-time", "cumulative-layout-shift"], "value": [perf_value, cleaned_fcp_value, cleaned_lcp_value, cleaned_fmp_value, cleaned_si_value, cleaned_tbt_value, cls_value], "score": [perf_score, fcp_score, lcp_score, fmp_score, si_score, tbt_score, cls_score] } df = pd.DataFrame(data_dict) # Append the DataFrame to the Excel file sheet_name = "Sheet1" if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] startrow = sheet.max_row for row in dataframe_to_rows(df, index=False, header=False): sheet.append(row) else: sheet = workbook.create_sheet(sheet_name) for row in dataframe_to_rows(df, index=False, header=True): sheet.append(row) print(f"Data extracted from {file_name} and appended to the Excel file") except KeyError as e: print(f"KeyError occurred while processing file '{file_name}': {e}") except json.JSONDecodeError as e: print(f"JSONDecodeError occurred while processing file '{file_name}': {e}") except Exception as e: print(f"An error occurred while processing file '{file_name}': {e}") def fileWatcher(my_dir: str, pollTime: int): excel_file_path = os.path.join(my_dir, 'output.xlsx') existingFiles = [] # Check if the output file already exists if os.path.isfile(excel_file_path): try: workbook = openpyxl.load_workbook(excel_file_path) existingFiles = jsonFilesInDirectory(my_dir) # Process the existing JSON files and append data to the Excel file doThingsWithNewFiles(existingFiles, my_dir, workbook) print("Existing JSON files processed and data appended to the Excel file") except openpyxl.utils.exceptions.InvalidFileException: workbook = openpyxl.Workbook() else: workbook = openpyxl.Workbook() # Check for new files at startup newFileList = jsonFilesInDirectory(my_dir) fileDiff = listComparison(existingFiles, newFileList) existingFiles = newFileList if len(fileDiff) > 0: # Process the new files and append data to the Excel file doThingsWithNewFiles(fileDiff, my_dir, workbook) # Save the Excel file workbook.save(excel_file_path) print(f"DataFrame exported to {excel_file_path}") while True: time.sleep(pollTime) # Get the updated list of JSON files in the directory newFileList = jsonFilesInDirectory(my_dir) # Find the difference between the previous and new file lists fileDiff = listComparison(existingFiles, newFileList) existingFiles = newFileList if len(fileDiff) > 0: # Process the new files and append data to the Excel file doThingsWithNewFiles(fileDiff, my_dir, workbook) # Save the Excel file workbook.save(excel_file_path) print(f"DataFrame exported to {excel_file_path}") def listComparison(originalList: list, newList: list): # Compare two lists and return the differences differencesList = [x for x in newList if x not in originalList] return differencesList my_dir = r"Z:" pollTime = 60 fileWatcher(my_dir, pollTime)

答案1

得分: 0

最简单的想法:获取自上次更新Excel文件以来更改的文件列表,使用os.path.getmtime获取Excel文件和所有JSON文件的最后更改时间,并选择那些更新的JSON文件。如果Excel文件存在,在启动时执行此操作,并处理所选的每个JSON文件,就好像它们是由监视程序检测到的一样。

然而,这可能会引入一些关于在断电附近处理的文件的歧义。因此,更准确的想法是:保存已处理的JSON文件列表,无论是在Excel文件内部还是在另一个地方(例如另一个文件或数据库中)。

甚至更精细的想法是使用一个数据库,将数据保存为与JSON文件相关联的键,将数据库用作唯一的真相来源,并根据需要从数据库生成Excel文件。

另外,覆盖Excel文件是可能的故障点。在这种情况下的一个良好做法是将数据写入同一目录中的临时文件,然后执行os.rename,这将原子地用新文件替换旧文件。

英文:

The simplest idea: To get the list of files changed since your last update to the Excel file, use os.path.getmtime to get the time of the last change of the Excel file and of all the JSON files, and select those JSON files that are newer. Do this at startup if the Excel file exists, and process each of the selected JSON files as if they were detected by the watcher.

However this could introduce some ambiguity about the files that are processed very near the power loss. So instead, the more accurate idea: save the list of processed JSON files, whether inside the Excel file, or in a separate place (e.g. another file, or a database).

An even more refined idea is to use a database where you save the data keyed to the JSON file, using the database as the single source of truth, and generate the Excel file from the database as needed.


As an aside, overwriting the Excel file is a possible point of failure. A good practice to do in this situation is to write to a temporary file in the same directory, then perform os.rename, which will atomically replace the old file with the new one.

答案2

得分: 0

以下是您要的代码翻译:

你可以创建一个文本文件其中存储了扫描文件的列表

更新了你的代码以检查文件是否存在并将文本文件写入

从 datetime 导入 datetime
导入 glob
导入 json
导入 openpyxl
从 openpyxl.utils.dataframe 导入 dataframe_to_rows
导入 os
导入 pandas 作为 pd
导入 time


def jsonFilesInDirectory(my_dir: str):
    # 获取目录中的 JSON 文件列表
    json_files = glob.glob(os.path.join(my_dir, "*.json"))

    return json_files


def clean_value(value):
    # 清理数值,去除不必要的字符
    return float(value.replace('\xa0s', '').replace('\xa0ms', '').replace(',', ''))


def doThingsWithNewFiles(fileDiff: list, my_dir: str, workbook):
    for file_name in fileDiff:
        file_path = os.path.join(my_dir, file_name)
        with open(file_path, 'r', encoding='utf-8') as file:
            try:
                json_data = json.load(file)

                # 从 JSON 文件中提取数据
                url = json_data["finalUrl"]
                fetch_time = json_data["fetchTime"]

                audits = json_data["audits"]
                fcp_metric = audits["first-contentful-paint"]["id"]
                fcp_value = audits["first-contentful-paint"]["displayValue"]
                fcp_score = audits["first-contentful-paint"]["score"]
                lcp_metric = audits["largest-contentful-paint"]["id"]
                lcp_value = audits["largest-contentful-paint"]["displayValue"]
                lcp_score = audits["largest-contentful-paint"]["score"]
                fmp_metric = audits["first-meaningful-paint"]["id"]
                fmp_value = audits["first-meaningful-paint"]["displayValue"]
                fmp_score = audits["first-meaningful-paint"]["score"]
                si_metric = audits["speed-index"]["id"]
                si_value = audits["speed-index"]["displayValue"]
                si_score = audits["speed-index"]["score"]
                tbt_metric = audits["total-blocking-time"]["id"]
                tbt_value = audits["total-blocking-time"]["displayValue"]
                tbt_score = audits["total-blocking-time"]["score"]
                cls_metric = audits["cumulative-layout-shift"]["id"]
                cls_value = audits["cumulative-layout-shift"]["displayValue"]
                cls_score = audits["cumulative-layout-shift"]["score"]

                categories = json_data["categories"]
                perf_metric = categories["performance"]["id"]
                perf_value = 0
                perf_score = categories["performance"]["score"]

                # 清理值并格式化提取时间
                cleaned_fcp_value = clean_value(fcp_value)
                cleaned_lcp_value = clean_value(lcp_value)
                cleaned_fmp_value = clean_value(fmp_value)
                cleaned_si_value = clean_value(si_value)
                cleaned_tbt_value = clean_value(tbt_value)
                datetime_obj = datetime.strptime(fetch_time, "%Y-%m-%dT%H:%M:%S.%fZ")
                cleaned_fetch_time = datetime_obj.strftime("%Y-%m-%d %H:%M:%S")

                # 为 DataFrame 创建数据字典
                data_dict = {
                    "fetch_time": [cleaned_fetch_time] * 7,
                    "url": 
* 7,
"metric": [ "performance", "first_contentful_paint", "largest_contentful_paint", "first-meaningful-paint", "speed-index", "total-blocking-time", "cumulative-layout-shift" ], "value": [ perf_value, cleaned_fcp_value, cleaned_lcp_value, cleaned_fmp_value, cleaned_si_value, cleaned_tbt_value, cls_value ], "score": [ perf_score, fcp_score, lcp_score, fmp_score, si_score, tbt_score, cls_score] } df = pd.DataFrame(data_dict) # 将 DataFrame 添加到 Excel 文件 sheet_name = "Sheet1" if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] else: sheet = workbook.create_sheet(sheet_name) for row in dataframe_to_rows(df, index=False, header=True): sheet.append(row) print(f"从 {file_name} 中提取数据并添加到 Excel 文件") except KeyError as e: print(f"在处理文件 '{file_name}' 时发生 KeyError: {e}") except json.JSONDecodeError as e: print(f"在处理文件 '{file_name}' 时发生 JSONDecodeError: {e}") except Exception as e: print(f"在处理文件 '{file_name}' 时发生错误: {e}") def fileWatcher(my_dir: str, pollTime: int): excel_file_path = os.path.join(my_dir, 'output.xlsx') existingFiles = [] if os.path.exists(os.path.join(os.getcwd(), 'scanned_files.txt')): with open('scanned_files.txt', 'a+') as f: existingFiles = f.read().split('\n') # 检查输出文件是否已经存在 if os.path.isfile(excel_file_path): try: workbook = openpyxl.load_workbook(excel_file_path) except openpyxl.utils.exceptions.InvalidFileException: workbook = openpyxl.Workbook() else: workbook = openpyxl.Workbook() # 处理现有的 JSON 文件并将数据添加到 Excel 文件 if not "Sheet1" in workbook.sheetnames: doThingsWithNewFiles(existingFiles, my_dir, workbook) print("已处理现有的 JSON 文件并将数据添加到 Excel 文件") # 在启动时检查新文件 while True: time.sleep(pollTime) # 获取目录中更新的 JSON 文件列表 newFileList = jsonFilesInDirectory(my_dir) # 查找之前和新文件列表之间的差异 fileDiff = listComparison(existingFiles, newFileList) existingFiles = newFileList if len(fileDiff) > 0: # 处理新文件并将数据添加到 Excel 文件 doThingsWithNewFiles(fileDiff, my_dir, workbook) # 保存 Excel 文件 workbook.save(excel_file_path) print(f"DataFrame 导出到 {excel_file_path}") with open('scanned_files.txt', 'w') as f: f.write('\n'.join(existingFiles)) def listComparison(originalList: list, newList: list): # 比较两个列表并返回差异 differencesList = [x for x in newList if x not in originalList] return differencesList my_dir = r"Z:" pollTime = 60 fileWatcher(my_dir, pollTime)

如果您有任何其他疑问,请随

英文:

You can create a text file that has the list of scanned files stored.

Updated your code, to read if exists and write the text file.

from datetime import datetime
import glob
import json
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
import os
import pandas as pd
import time
def jsonFilesInDirectory(my_dir: str):
# Get a list of JSON files in the directory
json_files = glob.glob(os.path.join(my_dir, "*.json"))
return json_files
def clean_value(value):
# Clean up numeric values by removing unnecessary characters
return float(value.replace('\xa0s', '').replace('\xa0ms', '').replace(',', ''))
def doThingsWithNewFiles(fileDiff: list, my_dir: str, workbook):
for file_name in fileDiff:
file_path = os.path.join(my_dir, file_name)
with open(file_path, 'r', encoding='utf-8') as file:
try:
json_data = json.load(file)
# Extract data from the JSON file
url = json_data["finalUrl"]
fetch_time = json_data["fetchTime"]
audits = json_data["audits"]
fcp_metric = audits["first-contentful-paint"]["id"]
fcp_value = audits["first-contentful-paint"]["displayValue"]
fcp_score = audits["first-contentful-paint"]["score"]
lcp_metric = audits["largest-contentful-paint"]["id"]
lcp_value = audits["largest-contentful-paint"]["displayValue"]
lcp_score = audits["largest-contentful-paint"]["score"]
fmp_metric = audits["first-meaningful-paint"]["id"]
fmp_value = audits["first-meaningful-paint"]["displayValue"]
fmp_score = audits["first-meaningful-paint"]["score"]
si_metric = audits["speed-index"]["id"]
si_value = audits["speed-index"]["displayValue"]
si_score = audits["speed-index"]["score"]
tbt_metric = audits["total-blocking-time"]["id"]
tbt_value = audits["total-blocking-time"]["displayValue"]
tbt_score = audits["total-blocking-time"]["score"]
cls_metric = audits["cumulative-layout-shift"]["id"]
cls_value = audits["cumulative-layout-shift"]["displayValue"]
cls_score = audits["cumulative-layout-shift"]["score"]
categories = json_data["categories"]
perf_metric = categories["performance"]["id"]
perf_value = 0
perf_score = categories["performance"]["score"]
# Clean up values and format the fetch time
cleaned_fcp_value = clean_value(fcp_value)
cleaned_lcp_value = clean_value(lcp_value)
cleaned_fmp_value = clean_value(fmp_value)
cleaned_si_value = clean_value(si_value)
cleaned_tbt_value = clean_value(tbt_value)
datetime_obj = datetime.strptime(fetch_time, "%Y-%m-%dT%H:%M:%S.%fZ")
cleaned_fetch_time = datetime_obj.strftime("%Y-%m-%d %H:%M:%S")
# Create a data dictionary for the DataFrame
data_dict = {
"fetch_time": [cleaned_fetch_time] * 7,
"url": 
* 7, "metric": [ "performance", "first_contentful_paint", "largest_contentful_paint", "first-meaningful-paint", "speed-index", "total-blocking-time", "cumulative-layout-shift" ], "value": [ perf_value, cleaned_fcp_value, cleaned_lcp_value, cleaned_fmp_value, cleaned_si_value, cleaned_tbt_value, cls_value ], "score": [ perf_score, fcp_score, lcp_score, fmp_score, si_score, tbt_score, cls_score] } df = pd.DataFrame(data_dict) # Append the DataFrame to the Excel file sheet_name = "Sheet1" if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] else: sheet = workbook.create_sheet(sheet_name) for row in dataframe_to_rows(df, index=False, header=True): sheet.append(row) print(f"Data extracted from {file_name} and appended to the Excel file") except KeyError as e: print(f"KeyError occurred while processing file '{file_name}': {e}") except json.JSONDecodeError as e: print(f"JSONDecodeError occurred while processing file '{file_name}': {e}") except Exception as e: print(f"An error occurred while processing file '{file_name}': {e}") def fileWatcher(my_dir: str, pollTime: int): excel_file_path = os.path.join(my_dir, 'output.xlsx') existingFiles = [] if os.path.exists(os.path.join(os.getcwd(), 'scanned_files.txt')): with open('scanned_files.txt', 'a+') as f: existingFiles = f.read().split('\n') # Check if the output file already exists if os.path.isfile(excel_file_path): try: workbook = openpyxl.load_workbook(excel_file_path) except openpyxl.utils.exceptions.InvalidFileException: workbook = openpyxl.Workbook() else: workbook = openpyxl.Workbook() # Process the existing JSON files and append data to the Excel file if not "Sheet1" in workbook.sheetnames: doThingsWithNewFiles(existingFiles, my_dir, workbook) print("Existing JSON files processed and data appended to the Excel file") # Check for new files at startup while True: time.sleep(pollTime) # Get the updated list of JSON files in the directory newFileList = jsonFilesInDirectory(my_dir) # Find the difference between the previous and new file lists fileDiff = listComparison(existingFiles, newFileList) existingFiles = newFileList if len(fileDiff) > 0: # Process the new files and append data to the Excel file doThingsWithNewFiles(fileDiff, my_dir, workbook) # Save the Excel file workbook.save(excel_file_path) print(f"DataFrame exported to {excel_file_path}") with open('scanned_files.txt', 'w') as f: f.write('\n'.join(existingFiles)) def listComparison(originalList: list, newList: list): # Compare two lists and return the differences differencesList = [x for x in newList if x not in originalList] return differencesList my_dir = r"Z:" pollTime = 60 fileWatcher(my_dir, pollTime)

Couldn't test the code, let me know if there's any issue with this.

huangapple
  • 本文由 发表于 2023年7月14日 08:53:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76684076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定