如何使用Python检查CSV文件中是否已存在数据 [英] How to check if an data already present in a CSV file using Python

查看:978
本文介绍了如何使用Python检查CSV文件中是否已存在数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在尝试编写一个python脚本,该脚本从文本文件中提取IP地址,请检查IP地址是否已存在CSV文件,如果IP地址已经存在,则不执行任何操作(通过),如果IP地址不存在,则将IP地址附加到CSV文件中。

I am trying to write a python script that picks up IP address(es) from a textfile, check if the IP addresses already present in CSV file, if IP address is already present then do nothing (pass), if the IP is not present in the CSV file then append the IP address in the CSV file.

我可以将IP地址添加到CSV文件中,但是我无法理解如何检查文件中是否已存在IP地址。

I can add the IP addresses to the CSV file but I am not able to get my head around with how to check if the IP address is already present in the file.

if os.path.isfile('IP_file.txt'):
    logfile = open('IP_file.txt', 'r')
    csv_file = open('csv_file.csv', 'ab')
    for line in logfile:
        if line in csv_file: # This is not working
            pass
        else:
            csv_file.write(line)
    csv_file.close()
    logfile.close()
else:
    print('No file with filename ' logfile 'created')

我也尝试使用CSV模块,但没有ck任何帮助深表感谢。

I also tried to use the CSV module but no luck. Any help is much appreciated.

推荐答案

CSV只是一种文本格式。逐行阅读,针对您的IP测试每一行。

CSV is just a text format. Read it line by line, test every line against your IP. Like

ip="192.168.1.1"
for line in csv_file:
    if ip in line:
        found = True
        break

我有点担心您的自行车文件放在磁盘上。最好将文件读入内存(首先在CSV文件中查找所有IP并放入列表中),然后再对列表进行检查,而不是为IP文件的每一行打开并遍历整个CSV文件。

I am a bit concerned against your cycling over file on the disk. Probably it is better to read files into memories (find all IPs in CSV file first and put in a list) and then check against the list instead of opening and iterating over whole CSV file for every line of IP file.

这篇关于如何使用Python检查CSV文件中是否已存在数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆