In Python, is there a concise way of comparing whether the contents of two text files are the same?

后端 未结 8 628
我在风中等你
我在风中等你 2020-11-29 01:51

I don\'t care what the differences are. I just want to know whether the contents are different.

8条回答
  •  清歌不尽
    2020-11-29 02:22

    If you're going for even basic efficiency, you probably want to check the file size first:

    if os.path.getsize(filename1) == os.path.getsize(filename2):
      if open('filename1','r').read() == open('filename2','r').read():
        # Files are the same.
    

    This saves you reading every line of two files that aren't even the same size, and thus can't be the same.

    (Even further than that, you could call out to a fast MD5sum of each file and compare those, but that's not "in Python", so I'll stop here.)

提交回复
热议问题