繁体   English   中英

如果它们已经在 txt 文件中,则从列表中删除它们

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM