Skip to main content
 首页 » 编程设计

python之如何检查文本文件是否变大了

2024年12月31日10oomusou

我的想法是创建一个脚本,在其中运行列表中的多个名称,然后比较它是否在 old_list 中。如果它不在列表中,那么我们打印出名称或调用一个函数。否则,如果它不在列表中,那么我只需等待 5-15 秒,然后再次检查是否添加了任何内容。

但是我现在的问题是我有一个随机名称的列表:

names.txt

Craig   
Rebekah   
Zina   
Stella   
Zachary   
Ila   
Delsie   
Mauro   
Alba   
Antoniette 
.... more 

使用这个脚本:

def script(): 
 
    old_list = [] 
    old_names_list = [line.rstrip('\n') for line in open('names.txt')] 
 
 
    while True: 
        new_names_list = [line.rstrip('\n') for line in open('newnames.txt')] 
 
        #if new name added to the list, then we call a random function, 
        #for example: def hello() or we can just print out the name 
        #and we continue to do the below. 
        for names in old_names_list: 
 
            if names not in old_list: 
                print(names) 
                #Call a random function etc def hello(): 
                old_list.append(names) 
 
        else: 
            randomtime = random.randint(5, 15) 
            print('No new names fouund! - retrying in {} secs'.format(randomtime)) 
            time.sleep(randomtime) 

newnames.txt

Rebekah   
Zina   
Stella   

现在它确实打印出列表中的所有名称,然后将其添加到 old_list 中,对于 for 循环中的下一次搜索,它不会打印出名称,因为它在旧列表。但是我想做的是,它应该检查 new_names_list 是否在列表中添加了新名称。如果有,它应该搜索名称是否在 names.txt 中,然后打印出添加的名称。

输出:

Prints out all the names and continue the while True loop. 
 
*Adding Craig to newnames.txt* 
 
print("Found Craig in the old_list!") 
 
continue to search if new names got added. 

请您参考如下方法:

这是你想要的吗? 它会一直循环下去,打印出所有找到的名字。

def script(): 
    old_names_list = [line.rstrip('\n') for line in open('names.txt')] 
    while True: 
        new_names_list = [line.rstrip('\n') for line in open('newnames.txt')] 
 
        if not new_names_list == old_names_list: #if there is a change 
            hell() #call that function 
            for i in new_names_list: 
                if not i in old_names_list: 
                    print(i) 
            old_names_list = new_names_list 
 
        else: #no change 
            print("no change") 
            time.sleep(5)