python csv.reader与两个不同word文档的比较问题

2024-06-10 11:30:26 发布

您现在位置:Python中文网/ 问答频道 /正文

有两个文件

A和B[具有相同的5列]

如果A和B具有相同的行数,下面的代码在捕获差异方面工作得非常好

newfile = csv.reader(open(todayfile,"r"))
oldfile = csv.reader(open(comparewith,"r"))
while True:
        try:
                newline = newfile.next()
                oldline = oldfile.next()
        if newline[0] == oldline[0] :
                    FailedServerList.append(newline[0])
                    FailedServerList.append(newline[3])
                    FailedServerList.append(str(newline[2])+" at "+str(datetime.strptime(newline[1],'%Y-%m-%d %H:%M:%S')))
                    FailedServerList.append(newline[4])
        except StopIteration:
                break

但是,如果其中一个文件的行数较多/较少,则比较不会得到正确的结果

我可以找到其他方法来做到这一点,但这个csv.reader看起来是一个不错的解决方案

What is that I could be missing or is it how csv.reader behaves?

我的工作解决方案是使用dict

newfile = csv.reader(open(todayfile,"r"))
oldfile = csv.reader(open(comparewith,"r"))
oldfiledict = dict()

for row in oldfile:
    oldfiledict[row[0]] = row[2]

for row in newfile:
    if row[0] in oldfiledict and row[2] != oldfiledict[row[0]]:
         FailedServerList.append(row[0])
         FailedServerList.append(row[3])
         FailedServerList.append(str(row[2])+" at "+str(datetime.strptime(row[1],'%Y-%m-%d %H:%M:%S')))
         FailedServerList.append(row[4])

Tags: 文件csvinnewlineopenreaderrowappend