Dictionary to csv File (Python)

0

my problem is that I have a csv file which happened to a dictionary. At the moment I want to pass this dictionary to a new csv file, the information is written but leaving a blank row, that is:

Instead of being like this:

'example 1': 'hello', 'example 2': 'hello2 ...
'example 3': 'hello', 'example 3': 'hello3 ...

looks like this:

'example 1': 'hello', 'example 2': 'hello2 ...

'example 1': 'hello', 'example 2': 'hello2 ...

I'm interested in erasing that blank line, the code I use for the writing part is:

    with open('datos_biblioteca.csv','a') as f:
        w = csv.writer(f)
        w.writerows(dic_escritura.items())

thanks.

    
asked by Sebastian Silva 31.01.2018 в 02:34
source

2 answers

0

You can try entering line by line with For

with open('datos_biblioteca.csv', 'w', newline='') as f:  si esta en python 2 en python 3 use 'w'
    w = csv.writer(f)
    for key, value in dic_escritura.items():
        w.writerow([key, value])

Python 2      with open('datos_biblioteca.csv', 'wb') as f: # use 'wb'

Python 3      with open('datos_biblioteca.csv', 'w', newline='') as f: # use 'w' y newline = ''

    
answered by 31.01.2018 / 02:43
source
0

Hello another option that you can use is pandas, you can check its documentation: link

import pandas as pd 

df = pd.read_csv('path_to_file')
data_dict = df.to_dict()
# haz algo con el diccionario
df.to_csv('salida.csv')
    
answered by 31.01.2018 в 05:41