lundi 5 septembre 2016

Python check if value in csv file

i got list of URLs, for example:

urls_list = [
    "http://yandex.ru",
    "http://google.ru",
    "http://rambler.ru",
    "http://google.ru",
    "http://gmail.ru",
    "http://mail.ru"
]

I need to open the csv file, check if each value from list in file - skip to next value, else (if value not in a list) add this value in list.

Result: 1st run - add all lines (if file is empty), 2nd run - doing nothing, because all elements in already in file.

A wrote code, but it's work completely incorrect:

import csv


urls_list = [
    "http://yandex.ru",
    "http://google.ru",
    "http://rambler.ru",
    "http://google.ru",
    "http://gmail.ru",
    "http://mail.ru"
]



with open('urls_list.csv', 'r') as fp:
    for row in fp:
        for url in urls_list:
            if url in row:
                print "YEY!"
            with open('urls_list.csv', 'a+') as fp:
                wr = csv.writer(fp, dialect='excel')
                wr.writerow([url])

Aucun commentaire:

Enregistrer un commentaire