[英]How to check if an data already present in a CSV file using Python
Good day all, 大家好
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地址的python脚本,检查CSV文件中是否已存在IP地址,如果已经存在IP地址,则不执行任何操作(通过),如果IP不存在在CSV文件中添加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. 我可以将IP地址添加到CSV文件中,但是我无法理解如何检查文件中是否已存在IP地址。
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')
I also tried to use the CSV module but no luck. 我也尝试使用CSV模块,但没有运气。 Any help is much appreciated. 任何帮助深表感谢。
CSV is just a text format. CSV只是一种文本格式。 Read it line by line, test every line against your IP. 逐行阅读,针对您的IP测试每一行。 Like 喜欢
ip="192.168.1.1"
for line in csv_file:
if ip in line:
found = True
break
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. 最好将文件读入内存(首先在CSV文件中找到所有IP,然后放入列表中),然后对照该列表进行检查,而不是为IP文件的每一行打开并遍历整个CSV文件。
Keep a list or dict that holds the unique fetched values: 保留一个包含唯一获取的值的列表或字典:
found_address = []
with open('IP_file.txt', 'r') as logfile:
with open('csv_file.csv', 'ab') as csv_file:
for line in logfile:
if not line in found_address:
csv_file.write(line)
found_address.append(line)
You are opening csv_file.csv in append mode ab
. 您正在以追加模式ab
打开csv_file.csv。 And then you are trying to check line in csv_file
. 然后,您尝试检查line in csv_file
。 In append-mode file-pointer points to the end-of-file. 在追加模式下,文件指针指向文件结尾。
little crazy functional-style python: 小小的疯狂的函数式python:
ip_file = set(map(str.strip, open('IP_file.txt').readlines()))
if CSV file is: 192.168.1.1,192.168.1.2,192.168.1.3,... 如果CSV文件是: 192.168.1.1,192.168.1.2,192.168.1.3,...
csv_file = set(map(str.strip, open('csv_file.csv').read().split(',')))
diff_ip = ip_file - csv_file
open('csv_file.csv','a').write(''.join(map(lambda x: ',{}'.format(x), list(diff_ip))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.