【发布时间】:2022-01-25 15:35:18
【问题描述】:
所以我有包含一些链接的 whitelist.txt 和包含其他链接的 scrapedlist.txt 以及 whitelist.txt 中的链接。
我正在尝试打开并阅读 whitelist.txt,然后打开并阅读 scrapedlist.txt - 写入新文件 updatedlist2.txt 将包含 scrapedlist.txt 减去 whitelist.txt.
的所有内容我对 Python 还是很陌生,所以还在学习。我已经搜索了答案,这就是我想出的:
def whitelist_file_func():
with open("whitelist.txt", "r") as whitelist_read:
whitelist_read.readlines()
whitelist_read.close()
unique2 = set()
with open("scrapedlist.txt", "r") as scrapedlist_read:
scrapedlist_lines = scrapedlist_read.readlines()
scrapedlist_read.close()
unique3 = set()
with open("updatedlist2.txt", "w") as whitelist_write2:
for line in scrapedlist_lines:
if unique2 not in line and line not in unique3:
whitelist_write2.write(line)
unique3.add(line)
我收到此错误,我也不确定我是否以正确的方式进行操作:
if unique2 not in line and line not in unique3:
TypeError: 'in <string>' requires string as left operand, not set
我应该怎么做才能实现上述以及我的代码是否正确?
编辑:
whitelist.txt:
KUWAIT
ISRAEL
FRANCE
scrapedlist.txt:
USA
CANADA
GERMANY
KUWAIT
ISRAEL
FRANCE
updatedlist2.txt(应该是这样):
USA
CANADA
GERMANY
【问题讨论】:
-
unique2 的用途是什么?你甚至不用任何地方的值来填充它
-
哦,那是存放whitelist.txt的行吗?我错了吗?
-
你也永远不会对 whitelist_read.readlines() 做任何事情......你没有将它分配给任何东西。
标签: python text-files with-statement