我如何让我的代码读取一堆按创建日期配对的文件,并在这些对中比较它们?

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

首先,我对 Python 一点也不擅长,所以我确信有更好的方法来解决这个问题,但是: 我有三个不同的代码,目前执行以下操作:

代码 1 和 2 分别获取一个 CSV 文件,删除不需要的列等并将其转换为 XSLX 文件 - 以下代码是代码 1 和 2 中所做的操作,仅更改文件本身的名称(Report1 与 Report2):

import pandas as pd
from datetime import date
from xlsxwriter.workbook import Workbook

# Read the CSV file (assuming the column is the first one)
df = pd.read_csv(f"C:/Users/User/Python/Project/Report1 -{date.today().year}-{date.today().month:02d}-{date.today().day:02d}.csv", header=None)

# Split the first column into separate columns based on spaces
max_commas = df[0].str.split(',').transform(len).max()
df[[f'name_{x}' for x in range(max_commas)]] = df[0].str.split(',', expand=True)

# Drop the original unnamed column
df.drop(0, axis=1, inplace=True)

# Drop the last column (name_0 - showing time of report)
df = df[df.columns.drop(list(df.filter(regex='name_0')))]

# Save the modified DataFrame to a new XLSX file
try:
    df.to_excel(f"Report1File {date.today().year}-{date.today().month:02d}-{date.today().day:02d}.xlsx", index=None)
except Exception as e:
    print(f"Error saving the file: {e}")

output_path = f"C:/Users/User/Python/Project/Report1 {date.today().year}-{date.today().month:02d}-{date.today().day:02d}.xlsx"
df.to_excel(output_path, index=None)
print(f"Result saved as {output_path}")

代码 3 使用上面代码 1 和 2 中的两个输出 Excel 文件作为输入。如上所示,文件以日期后缀命名,例如“Report1File 02.04.2024”和“Report2File 02.04.2024”。然后比较这两个文件以查找任何差异,并告诉我是否发现任何差异:

import pandas as pd
from datetime import date
from xlsxwriter.workbook import Workbook

import Report1
import Report2

Report1
Report2

# Read the Excel files
df1 = pd.read_excel(f"Report1File {date.today().year}-{date.today().month:02d}-{date.today().day:02d}.xlsx", skiprows=[2])
df2 = pd.read_excel(f"Report2File {date.today().year}-{date.today().month:02d}-{date.today().day:02d}.xlsx", skiprows=[3])

# Compare the dataframes
differences = df1.compare(df2)

if differences.empty:
    print("None found")

else:
    print("Differences found in:")
    print(differences)

现在,我需要让代码读取单个文件夹中的一堆文件,其中文件与相同的日期配对。例如:

-“Report1File 02.04.2024”和“Report2File 02.04.2024”

-“Report1File 01.04.2024”和“Report2File 01.04.2024”等等

我希望代码比较配对的文件,并告诉我“Report1File 02.04.2024”和“Report2File 02.04.2024”之间以及“Report1File 01.04.2024”和“Report2File 01.04.2024”之间是否有任何差异.

目前不知道如何继续,所以我不知道该尝试什么:-)

我看到其他帖子可能有类似的问题,但不确定如何在我的代码中实现解决方案

python comparison
1个回答
0
投票

假设每天总是有两个文件(没有其他文件)

import os

files = os.listdir("the directory")
files.sort()

reports1 = files[:len(files)//2]
reports2 = files[len(files)//2:]

for file1,file2 in zip(reports1,reports2):
    ...

我强烈建议将 Report1 和 Report2 作为一个函数,并将请求的文件名传递给它

def Report(filename):
    df = pd.read_csv(f"C:/Users/User/Python/Project/{filename} -{date.today().year}-{date.today().month:02d}-{date.today().day:02d}.csv", header=None)
    ...
© www.soinside.com 2019 - 2024. All rights reserved.