简体   繁体   English

您能否将一个具有固定单词列表的文件与一个在 python 中每 10 秒更新一次单词的文件进行比较?

[英]Can you compare one file with fixed list of words with one file which is being updated with words every 10 seconds in python?

f1 = open("C:/Users/user/Documents/intro.txt", "r")  
f2 = open("C:/Users/user/Desktop/intro1.txt", "r")  
  
i = 0
  
for line1 in f1:
    i += 1
      
    for line2 in f2:
          
        
        if line1 == line2:  
            print("Line ", i, ": IDENTICAL")       
        else:
            print("Line ", i, ":")
            print("\tFile 1:", line1, end='')
            print("\tFile 2:", line2, end='')
        break
f1.close()                                       
f2.close() 

Can this method be used to compare them?这种方法可以用来比较它们吗?
I tried alot of methods but i dont see any solutions If anyone could help me that would be great!我尝试了很多方法,但我没有看到任何解决方案如果有人可以帮助我,那就太好了! I am fairly new to python我对 python 相当陌生

The above code would compare every line in the file to every line in the other file for each line.上面的代码会将文件中的每一行与另一个文件中的每一行进行比较。 You would want to compare them by the same index.您可能希望通过相同的索引来比较它们。

with open("C:/Users/user/Documents/intro.txt", "r") as f1:
    lines1 = f1.readlines()

with open("C:/Users/user/Desktop/intro1.txt", "r") as f2:
    lines2 = f2.readlines()

length1 = len(lines1)
length2 = len(lines2)

if length1 == length2:
    for i in range(length1):
        line1 = lines1[i]
        line2 = lines2[i]

        if lines1[i] == lines2[i]:
            print("Line ", i, ": IDENTICAL")
        else:
            print("Line ", i, ":")
            print("\tFile 1:", line1, end='')
            print("\tFile 2:", line2, end='')
            break
else:
    print("Unequal length: ", length1, " ", length2)

In addition to my upper comment, here is the code to easy make hash for a file:除了我上面的评论,这里是轻松为文件制作 hash 的代码:

import hashlib

def hash_file(filename):
   """"This function returns the SHA-1 hash
   of the file passed into it"""

   # make a hash object
   h = hashlib.sha1()

   # open file for reading in binary mode
   with open(filename,'rb') as file:

       # loop till the end of the file
       chunk = 0
       while chunk != b'':
           # read only 1024 bytes at a time
           chunk = file.read(1024)
           h.update(chunk)

   # return the hex representation of digest
   return h.hexdigest()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM