我正在撰寫一個程式來比較兩個檔案路徑之間的所有檔案和目錄(基本上檔案元資料、內容和內部目錄應該匹配)
檔案內容比較是逐行進行的。csv 的尺寸可能相同也可能不同,但以下方法通常管理尺寸不相同的場景。
問題是處理時間太慢。
一些背景關系:
- 使用filecmp識別這兩個檔案不同
- 這個特別有問題的 csv 大約有 11k 列和 800 行。
- 我的程式不會事先知道 csv 中的資料型別是什么,因此不能選擇為 pandas 定義 dtype
- 如果 csv 檔案很小,Difflib 會做得很好,但不適用于這個特定的用例
我查看了關于 SO 的所有相關問題,并嘗試了這些方法,但處理時間很糟糕。方法 3 給出了奇怪的結果
方法1(熊貓) - 可怕的等待,我不斷收到這個錯誤
UserWarning:您正在合并 int 和 float 列,其中 float 值不等于它們的 int 表示形式。
import pandas as pd
import numpy as np
df1 = pd.read_csv(f1)
df2 = pd.read_csv(f2)
diff = df1.merge(df2, how='outer', indicator='exists').query("exists!='both'")
print(diff)
方法 2 (Difflib) - 等待這個巨大的 csv
import difflib
def CompareUsingDiffLib(f1, f2 ):
html = h.make_file(file1_lines, file2_lines, context=True,numlines=0)
htmlfilepath = filePath "\\htmlFiles"
with open(htmlfilepath, 'w') as fh:
fh.write(html)
with open (file1) as f, open(file2) as z:
f1 = f.readlines()
f2 = z.readlines()
CompareUsingDiffLib(f1, f2 )
方法 3(純 python)- 不正確的結果
with open (f1) as f, open(f2) as z:
file1 = f.readlines()
file2 = z.readlines()
# check row number of diff in file 1
for line in file1:
if line not in file2:
print(file1.index(line))
# it shows from all the row from row number 278 to last row
# is not in file 2, which is incorrect
# I checked using difflib, and using excel as well
# no idea why the results are like that
# running below code shows the same result as the first block of code
for line in file2:
if line not in file1:
print(file2.index(line))
方法 4 (csv-diff) - 可怕的等待
from csv_diff import load_csv, compare
diff = compare(
load_csv(open("one.csv")),
load_csv(open("two.csv"))
)
任何人都可以幫忙:
- 處理時間更短的方法
- 除錯方法三
uj5u.com熱心網友回復:
將檔案與成員進行比較readlines()并僅測驗成員身份(“這在那個?”)并不等于區分行。
with open (f1) as f, open(f2) as z:
file1 = f.readlines()
file2 = z.readlines()
for line in file1:
if line not in file2:
print(file1.index(line))
考慮以下兩個 CSV:
file1.csv file2.csv
----------- -----------
a,b,c,d a,b,c,d
1,2,3,4 1,2,3,4
A,B,C,D i,ii,iii,iv
i,ii,iii,iv A,B,C,D
該腳本不會產生任何結果(并給人一種沒有差異的錯誤印象),因為檔案 1 中的每一行都在檔案2 中,即使檔案逐行不同。(不過,我不能說為什么你認為你得到了誤報,但沒有看到這些檔案。)
我建議使用 CSV 模塊并逐行迭代檔案,甚至逐列迭代:
import csv
path1 = "file1.csv"
path2 = "file2.csv"
with open(path1) as f1, open(path2) as f2:
reader1 = csv.reader(f1)
reader2 = csv.reader(f2)
for i, row1 in enumerate(reader1):
try:
row2 = next(reader2)
except StopIteration:
print(f"Row {i 1}, f1 has this extra row compared to f2")
continue
if row1 == row2:
continue
if len(row1) != len(row2):
print(f"Row {i 1} of f1 has {len(row1)} cols, f2 has {len(row2)} cols")
continue
for j, cell1 in enumerate(row1):
cell2 = row2[j]
if cell1 != cell2:
print(f'Row {i 1}, Col {j 1} of f1 is "{cell1}", f2 is "{cell2}"')
for row2 in reader2:
i = 1
print(f"Row {i 1}, f2 has this extra row compared to f1")
這使用 file1 的迭代器來驅動 file2 的迭代器,通過僅在 file1 的行數多于 file2 時記錄例外來解釋兩個檔案之間行數的任何差異,StopIteration如果還有任何行要讀入則列印差異file2 (reader2) 在最底部。
當我對這些檔案運行它時:
file1 file2
----------- ----------
a,b,c,d a,b,c
1,2,3,4 1,2,3,4
A,B,C,D A,B,C,Z
i,ii,iii,iv i,ii,iii,iv
x,xo,xox,xoxo
我得到:
Row 1 of f1 has 4 cols, f2 has 3 cols
Row 3, Col 4 of f1 is "D", f2 is "Z"
Row 5, f2 has an extra row compared to f1
如果我交換 path1 和 path2,我會得到:
Row 1 of f1 has 3 cols, f2 has 4 cols
Row 3, Col 4 of f1 is "Z", f2 is "D"
Row 5, f1 has this extra row compared to f2
它做得很快。我模擬了兩個 800 x 11_000 CSV,行之間的差異非常非常小(如果有的話),它在用戶時間不到一秒的時間內處理了所有差異(不計算列印)。
uj5u.com熱心網友回復:
use 可以filecmp用來逐位元組比較兩個檔案。檔案
執行
>>> import filecmp
>>> filecmp.cmp('somepath/file1.csv', 'otherpath/file1.csv')
True
>>> filecmp.cmp('somepath/file1.csv', 'otherpath/file2.csv')
True
注意:檔案名無關緊要。
與散列的速度比較:https ://stackoverflow.com/a/1072576/16239119
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486681.html
