Python importa csv a la lista [duplicado]

Resuelto MorganTN asked hace 10 años • 0 respuestas

Tengo un archivo CSV con unos 2000 registros.

Cada registro tiene una cadena y una categoría:

This is the first line,Line1
This is the second line,Line2
This is the third line,Line3

Necesito leer este archivo en una lista similar a esta:

data = [('This is the first line', 'Line1'),
        ('This is the second line', 'Line2'),
        ('This is the third line', 'Line3')]

¿Cómo puedo importar este CSV a la lista que necesito usando Python?

MorganTN avatar Jul 10 '14 02:07 MorganTN
Aceptado

Usando el módulo csv :

import csv

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    data = list(reader)

print(data)

Producción:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]

Si necesitas tuplas:

import csv

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    data = [tuple(row) for row in reader]

print(data)

Producción:

[('This is the first line', 'Line1'), ('This is the second line', 'Line2'), ('This is the third line', 'Line3')]

Antigua respuesta de Python 2, que también usa el csvmódulo:

import csv
with open('file.csv', 'rb') as f:
    reader = csv.reader(f)
    your_list = list(reader)

print your_list
# [['This is the first line', 'Line1'],
#  ['This is the second line', 'Line2'],
#  ['This is the third line', 'Line3']]
Maciej Gol avatar Jul 09 '2014 19:07 Maciej Gol

Actualizado para Python 3 :

import csv

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    your_list = list(reader)

print(your_list)

Producción:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]
seokhoonlee avatar Feb 11 '2016 13:02 seokhoonlee

Pandas es bastante bueno manejando datos. Aquí hay un ejemplo de cómo usarlo:

import pandas as pd

# Read the CSV into a pandas data frame (df)
#   With a df you can do many things
#   most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')

# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]

# or export it as a list of dicts
dicts = df.to_dict().values()

Una gran ventaja es que pandas se ocupa automáticamente de las filas de encabezado.

Si no has oído hablar de Seaborn , te recomiendo que le eches un vistazo.

Ver también: ¿ Cómo leo y escribo archivos CSV con Python?

Pandas #2

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
dicts = df.to_dict('records')

El contenido de df es:

     country   population population_time    EUR
0    Germany   82521653.0      2016-12-01   True
1     France   66991000.0      2017-01-01   True
2  Indonesia  255461700.0      2017-01-01  False
3    Ireland    4761865.0             NaT   True
4      Spain   46549045.0      2017-06-01   True
5    Vatican          NaN             NaT   True

El contenido de los dictados es

[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
 {'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
 {'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
 {'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
 {'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
 {'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]

Pandas #3

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]

El contenido de listses:

[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
 ['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
 ['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
 ['Ireland', 4761865.0, NaT, True],
 ['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
 ['Vatican', nan, NaT, True]]
Martin Thoma avatar Nov 24 '2016 13:11 Martin Thoma

Actualización para Python3:

import csv
from pprint import pprint

with open('text.csv', newline='') as file:
    reader = csv.reader(file)
    res = list(map(tuple, reader))

pprint(res)

Producción:

[('This is the first line', ' Line1'),
 ('This is the second line', ' Line2'),
 ('This is the third line', ' Line3')]

Si csvfile es un objeto de archivo, debe abrirse con newline=''.
módulo csv

Wizard avatar Jan 05 '2018 03:01 Wizard

Si está seguro de que no hay comas en su entrada, excepto para separar la categoría, puede leer el archivo línea por línea y dividirlo, , luego enviar el resultado aList

Dicho esto, parece que estás viendo un archivo CSV, por lo que podrías considerar usar los módulos correspondientes.

Miquel avatar Jul 09 '2014 19:07 Miquel