Python csv string to array


¿Alguien conoce una simple biblioteca o función para analizar una cadena codificada en csv y convertirla en un array o diccionario?

No creo que quiera el módulo csv construido en porque en todos los ejemplos que he visto que toma rutas de archivo, no cadenas.

Author: thefourtheye, 2010-07-22

10 answers

Usaría StringIO:

try:
    # for Python 2.x
    from StringIO import StringIO
except ImportError:
    # for Python 3.x
    from io import StringIO
import csv

scsv = """text,with,Polish,non-Latin,lettes
1,2,3,4,5,6
a,b,c,d,e,f
gęś,zółty,wąż,idzie,wąską,dróżką,
"""

f = StringIO(scsv)
reader = csv.reader(f, delimiter=',')
for row in reader:
    print('\t'.join(row))

Versión más simple con split() en nuevas líneas:

reader = csv.reader(scsv.split('\n'), delimiter=',')
for row in reader:
    print('\t'.join(row))

O puede simplemente split() esta cadena en líneas usando \n como separador, y luego split() cada línea en valores, pero de esta manera debe tener en cuenta las comillas, por lo que se prefiere usar el módulo csv.

 185
Author: Michał Niklas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-17 14:05:28

Simple-el módulo csv también funciona con listas:

>>> a=["1,2,3","4,5,6"]  # or a = "1,2,3\n4,5,6".split('\n')
>>> import csv
>>> x = csv.reader(a)
>>> list(x)
[['1', '2', '3'], ['4', '5', '6']]
 55
Author: adamk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-22 05:30:53

Como ya han señalado otros, Python incluye un módulo para leer y escribir archivos CSV. Funciona bastante bien siempre y cuando los caracteres de entrada se mantengan dentro de los límites ASCII. En caso de que desee procesar otras codificaciones, se necesita más trabajo.

La documentación de Python para el módulo csv implementa una extensión de csv.reader, que utiliza la misma interfaz pero puede manejar otras codificaciones y devuelve cadenas unicode. Simplemente copie y pegue el código de la documentación. Despues eso, puede procesar un archivo CSV como este:

with open("some.csv", "rb") as csvFile: 
    for row in UnicodeReader(csvFile, encoding="iso-8859-15"):
        print row
 8
Author: roskakori,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-22 19:05:06
>>> a = "1,2"
>>> a
'1,2'
>>> b = a.split(",")
>>> b
['1', '2']

Para analizar un archivo CSV:

f = open(file.csv, "r")
lines = f.read().split("\n") # "\r\n" if needed

for line in lines:
    if line != "": # add other needed checks to skip titles
        cols = line.split(",")
        print cols
 8
Author: nvd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-08 12:21:04

El oficial doc para csv.reader() https://docs.python.org/2/library/csv.html es muy útil, que dice:

Los objetos de archivo y los objetos de lista son adecuados

import csv

text = """1,2,3
a,b,c
d,e,f"""

lines = text.splitlines()
reader = csv.reader(lines, delimiter=',')
for row in reader:
    print('\t'.join(row))
 5
Author: soulmachine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-23 01:11:40

Por la documentación:

Y aunque el módulo no soporta directamente el análisis de cadenas, se puede hacer fácilmente:

import csv
for row in csv.reader(['one,two,three']):
    print row

Simplemente convierte tu cadena en una sola lista de elementos.

Importar StringIO me parece un poco excesivo cuando este ejemplo está explícitamente en los documentos.

 5
Author: roundar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-22 08:23:48

Https://docs.python.org/2/library/csv.html?highlight=csv#csv.reader

Csvfile puede ser cualquier objeto que soporte el protocolo iterator y devuelve una cadena cada vez que se llama a su método next ()

Así, un StringIO.StringIO(), str.splitlines() o incluso un generador son todos buenos.

 3
Author: ivan_pozdeev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-13 22:12:03

Use esto para tener un csv cargado en una lista

import csv

csvfile = open(myfile, 'r')
reader = csv.reader(csvfile, delimiter='\t')
my_list = list(reader)
print my_list
>>>[['1st_line', '0'],
    ['2nd_line', '0']]
 2
Author: JimS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-05 12:45:10

Aquí hay una solución alternativa:

>>> import pyexcel as pe
>>> text="""1,2,3
... a,b,c
... d,e,f"""
>>> s = pe.load_from_memory('csv', text)
>>> s
Sheet Name: csv
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| a | b | c |
+---+---+---+
| d | e | f |
+---+---+---+
>>> s.to_array()
[[u'1', u'2', u'3'], [u'a', u'b', u'c'], [u'd', u'e', u'f']]

Aquí está la documentación

 1
Author: chfw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-03 13:46:40

Panda es bastante potente e inteligente biblioteca de lectura CSV en Python

Un ejemplo simple aquí, tengo un ejemplo.archivo zip con cuatro archivos en él.

EXAMPLE.zip
 -- example1.csv
 -- example1.txt
 -- example2.csv
 -- example2.txt

from zipfile import ZipFile
import pandas as pd


filepath = 'EXAMPLE.zip'
file_prefix = filepath[:-4].lower()

zipfile = ZipFile(filepath)
target_file = ''.join([file_prefix, '/', file_prefix, 1 , '.csv'])

df = pd.read_csv(zipfile.open(target_file))

print(df.head()) # print first five row of csv
print(df[COL_NAME]) # fetch the col_name data

Una vez que tenga datos puede manipular para jugar con una lista u otros formatos.

 0
Author: WEBBYFOX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-16 11:41:32