[英]Remove items from list if they are already in txt file
我試圖運行這段代碼,但我遇到了問題,它沒有按我的需要工作。
我需要檢查項目列表中的代碼是否已經保存在 file.txt 中,如果它已經存在,我需要從列表中刪除該項目。
然后將項目列表作為字符串保存在新的 file.txt 中
items = [['e5860', '2020-06-10'], ['e6056', '2020-06-10'], ['e6008', '2020-06-10'], ['100080020', '2020-06-10'], ['e6463', '2020-06-10'], ['KW13012', '2020-06-10'], ['e3589', '2020-06-10']]
for i, item in enumerate(items):
with open('file.txt') as f:
if item[0] in f.read():
items.pop(items.index(item))
with open('file.txt', 'w') as f:
f.write(str(items))
print(items)
當我第一次運行此代碼時,file.txt 將為空,因此 output 應該是:
[['e5860', '2020-06-10'], ['e6056', '2020-06-10'], ['e6008', '2020-06-10'], ['100080020', '2020-06-10'], ['e6463', '2020-06-10'], ['KW13012', '2020-06-10'], ['e3589', '2020-06-10']]
然后,如果我再次運行相同的代碼,output 應該是一個空項目列表(因為它們之前都保存在文件中並從列表中刪除)。
但是當我運行這個第一個 output 是正確的,我從項目中獲取列表,如果我再次運行它,那么我得到這個 output:
[['e6056', '2020-06-10'], ['100080020', '2020-06-10'], ['KW13012', '2020-06-10']]
為什么這個代碼沒有從列表中刪除?
如果要將列表保存為列表,可以使用 json 模塊對其進行序列化。 這將讓您輕松加載和保存列表。
然后,您可以加載文件並處理一個數據結構,以便您輕松測試是否包含在內。 一套是顯而易見的選擇。 一旦你有了它,你可以根據項目是否在這個集合中過濾你的列表,然后將列表轉儲回文件。
這假設一個文件已經存在(即使它是空的):
items = [['e5860', '2020-06-10'], ['e6056', '2020-06-10'], ['e6008', '2020-06-10'], ['100080020', '2020-06-10'], ['e6463', '2020-06-10'], ['KW13012', '2020-06-10'], ['e3589', '2020-06-10']]
with open(filePath, 'r') as f:
data = f.read()
if data:
file_items = json.loads(data)
# create a set of just the first items in the sub lists:
seen = set(item[0] for item in file_items)
else: # empty file, make an empty set
seen = set()
filtered = [item for item in items if item[0] not in seen]
print(filtered)
with open(filePath, 'w') as f:
json.dump(filtered,f)
這將在一個空文件和一個包含所有items
的 json 的文件之間交替
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.