将最新CSV与目录中的所有CSV进行比较,删除最新CSV中的匹配项,并使用python在新文件中写入新行

xcitsw88  于 2023-03-10  发布在  Python
关注(0)|答案(1)|浏览(127)

例如当文件名是其它名称时,代码将不能正常工作。
例如,当文件名是carre123. csv时,它不能正确比较。但是当我将文件名改为test123. csv时,它工作正常。
这是密码

import os
import pandas as pd

# Set the directory where the CSV files are stored
directory = '/PATH/csv-files'

# Get a list of all the CSV files in the directory
csv_files = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('.csv')]
#print(csv_files)

# Sort the CSV files by modification time and select the last file as the latest file
latest_file = sorted(csv_files, key=os.path.getmtime)[-1]
#print(latest_file)

# Read the contents of the latest CSV file into a pandas DataFrame
latest_data = pd.read_csv(latest_file)
#print(latest_data)

# Iterate over all the previous CSV files
for csv_file in csv_files[:-1]:
    # Read the contents of the previous CSV file into a pandas DataFrame
    prev_data = pd.read_csv(csv_file)
    #print(prev_data)

    # Identify the rows in the latest CSV file that match the rows in the previous CSV file
    matches = latest_data.isin(prev_data.to_dict('list')).all(axis=1)
    print(matches)

    # Remove the matching rows from the latest CSV file
    latest_data = latest_data[~matches]

# Write the remaining rows in the latest CSV file to a new file
latest_data.to_csv('/NEWPATH/diff.csv', index=False)

当文件名是carre123. csv时,它不能正确比较。但是当我将文件名改为test123. csv时,它工作正常。

eit6fx6z

eit6fx6z1#

我认为你的代码有一个bug,这可能是导致问题的原因。for循环在csv_files[:-1]上,csv_files[:-1]没有按修改时间排序,所以根据文件名,这可能会导致循环包含latest_file。尝试存储排序列表sorted(csv_files, key=os.path.getmtime),然后为latest_file选择最后一个,并循环剩余的文件。也许还有其他问题,但根据您提供的示例,这看起来是我所能看到的唯一明显的问题。

相关问题