比较 sql 个文件时将比较写入 .txt 文件

Writing comparison to .txt file when comparing sql files

所以我尝试使用 Python 脚本比较多个表。实际比较是有效的,用 print 语句测试过,但写入 .txt 文件不是。我相信我的语法可能有错误,虽然我对 Python 比较陌生,但我找不到它。

for num in range(0, 4): #runs through the database array and compares the files in each folder
    comp_var = directory + server_number[size] + databases[num]
    for file in os.listdir(comp_var):     
        for num1 in  os.listdir(master + databases[num]):  
            var = master + databases[num] + "\" + os.listdir(master + databases[num])[size]
            for line in open(var, 'r'):
                for line2 in open(comp_var + "\" + file, 'r'):
                    same = set(line).intersection(line2)
                    print(same)
                same.discard('\n')
            with open('results.txt', 'w') as file_out:
                for line1 in same:
                    file_out.write(line1)
            size = size + 1
            comp_var = directory + server_number[size] + databases[num]            
        size = 0

您的问题是每次调用打开时都会创建一个新文件。您应该使用 'a' 附加到文件,这可能是您想要的。

您正在覆盖 results.txt

with open('results.txt', 'w') as file_out:

改为:

with open('results.txt', 'a') as file_out:

来自 Python documentation:

'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end.