繁体   English   中英

Python3 - 如何迭代和删除 CSV 中的条目?

[英]Python3 - How can I iterate and remove the entry in CSV?

之前,我有一个节点列表。 因此,我很容易进行迭代,如果命令成功运行,则删除该条目,并在 1 小时后将其余条目写回文件。 而不是 1 个命令的 1 个变量,现在我有 4 个不能放在列表中的变量。 经过一番研究,我发现 CSV 是附加文件的最佳解决方案,而不是 JSON。 如何按照我列出的方式迭代和删除 CSV 中的条目?

stop_time = datetime.datetime.now() + datetime.timedelta(hours=1)
while list_file:
        list_iterate = list_file.copy()
        for i in list_iterate:
            cmd = f'some bash cmd'
            value = subprocess.check_output(cmd, shell=True).decode("utf-8").strip()
            if value == '0':
                list_file.remove(i)
        if datetime.datetime.now() > stop_time:
            completed = False
            with open("list_file.txt", "w") as file:
               file.write(list_file)
            break

示例 CSV

cluster1,pool1, abc
cluster1,pool2,bcb
cluster2,pool1,abc

您可以将 CSV 文件转换为列表,然后从中删除。 示例片段(修改/扩展以包括 1 小时延迟等):

with open("path/to/inputfile.csv", "r") as infile:
    list_file = infile.readlines()

index = 1
list_file.remove(index)

with open("path/to/outputfile.csv","w") as outfile:
    outfile.writelines(list_file)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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