H
H
hardwellZero2015-05-23 21:54:45
Python
hardwellZero, 2015-05-23 21:54:45

How to write to csv?

Good evening, Toaster;)
I'm trying to write several values ​​from different sheets into a csv file.

list1 = ['1', '2', '3']
list2 = ['a', 'b', 'c']
list3 = ['x', 'y', 'z']

As a result, I want to get:
1, a, x
2, b, y
3, c, z

Now I write like this:
resultFile = open("test.csv",'wb')
wr = csv.writer(resultFile, delimiter='\n')
wr.writerow(list1)

But this only writes the elements from the first sheet, how to add the rest?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sim3x, 2015-05-23
@hardwellZero

list1 = ['1', '2', '3']
list2 = ['a', 'b', 'c']
list3 = ['x', 'y', 'z']

with open('eggs.csv', 'wb') as f:
    wr = csv.writer(f)
    wr.writerows([(list1[i], list2[i], list3[i]) for i in range(len(list1))])

L
lPolar, 2015-05-25
@lPolar

Well, what a stupid habit of handicraft - element-by-element loops and line-by-line saving.
Use high level tools.

import pandas as pd
list1 = ['1', '2', '3']
list2 = ['a', 'b', 'c']
list3 = ['x', 'y', 'z']
frame = pd.DataFrame([list1,list2,list3]) # собираем фрейм
frame.to_csv('my_csv_export.csv',index=False) #экспортируем в файл

V
vikholodov, 2017-08-09
@vikholodov

What if the arrays are formed in a loop, how to write each array in a separate column? I just overwrite a column

def main():
    keyword = ['окна', 'окна ПВХ']

    for i in keyword:
        url = 'https://yandex.ru/search/?text='+i+'&lr=22&rstr=-22'
        all_links = get_all_links(get_html(url)) #получаем список ссылок по ключевому слову i
        for links in all_links:
            frame = pd.DataFrame(all_links, columns=[i])  # собираем фрейм
            frame.to_csv('my_csv_export.csv', index=False)  # экспортируем в файл

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question