E
E
exded2017-03-24 20:19:43
Python
exded, 2017-03-24 20:19:43

Python writing data to csv?

There is a cycle for writing pictures, it works well parsing all the pictures that are needed, but when it comes to writing to csv, only the first value is taken.

IMG = 'css  селекторы'

r = reqests.get('url').text
f = fromstring(f)

df = DataFrame(columns=('загаловки'))

slovar = [(заголовки, переменные),]


for image in f.cssselect(IMG):
    u = image.cssselect('img')[0]
    un = u.get('src')
    unn = urljoin(URL, un)
    t = requests.get(unn)
    k = open('image/%s' % un.split('/')[-1], 'wb')
    slovar.append(('img',  un.split('/')[-1])) #запись в словарь
    k.write(t.content)
    k.close()
    df = df.append(dict(slovar), ignore_index=True)

df.to_csv('foto.csv', index=False, sep=';')

Why is only the first value written? After all, it is nested in a cycle

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex P., 2017-03-24
@exded

and if you file it like this:
first you write to the dictionary in a loop, and then you write the dictionary to csv ..
in the code it will be something like this ..

with open('image/%s' % un.split('/')[-1], 'wb') as f:
        w = csv.writer(f)
        for item in a:
            w.writerow([item])
    f.close()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question