我有 2 個包含電子郵件地址的檔案,其中一些電子郵件地址是相同的,而有些則不是。我需要查看file1 中的哪些電子郵件地址不在file2 中。我怎樣才能做到這一點?如果我也可以將它們放入串列中,那就太好了。
這是我得到的:
'file1 = open("competitor_accounts.txt")
file2 = open("accounts.txt")'
我知道這并不多,但我需要幫助開始
我想也許使用帶有 if 陳述句的 for 回圈?但我只是不知道怎么做。
uj5u.com熱心網友回復:
您可以將每個檔案的內容讀取到單獨的串列中,然后像這樣將串列相互比較
with open('accounts.txt') as f:
accounts = [line for line in f]
with open('competitor_accounts.txt') as f:
competitors = [line for line in f]
accounts_not_competitors = [line for line in accounts if line not in competitors]
competitors_not_accounts = [line for line in competitors if line not in accounts]
您也可以使用openwithreadlines()但 using通常更容易接受,因為您在閱讀完檔案后with不需要顯式顯示該檔案。close()
file_a = open('accounts.txt')
accounts = file_a.readlines()
file_a.close()
最后的兩行形成一個運算式,以根據現有串列中的匹配項生成一個新串列。這些可以寫成更簡單的形式:
accounts_not_competitors = []
for line in accounts:
if line not in competitors:
accounts_not_competitors.append(line)
我相信這應該足以讓您開始使用語法和功能,以防您想在兩者之間進行一些其他比較。
uj5u.com熱心網友回復:
假設每個檔案中只有一封電子郵件是一行
首先將每個檔案保存在一個串列中,然后創建另一個串列來保存差異。
遍歷 file1 串列并檢查 file1 串列中的每個專案是否存在于 file2 串列中,如果沒有將該專案添加到差異串列中
f1_list = []
f2_list = []
diff = []
with open(file1name, 'r', encoding='utf-8') as f1:
for line in f1:
f1_list.append(line)
with open(file2name, 'r', encoding='utf-8') as f2:
for line in f2:
f2_list.append(line)
for email in f1_list:
if not email in f2_list:
diff.append(email)
print(diff)
uj5u.com熱心網友回復:
您可以使用set
with open('competitor_accounts.txt', 'r') as file:
competitor_accounts = set([mail for mail in file])
with open('accounts.txt', 'r') as file:
accounts = set([mail for mail in file])
result = list(competitor_accounts - accounts)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/511779.html
上一篇:嘗試在C中讀取檔案時檔案內容無效
