Python import csv naar lijst

Ik heb een CSV-bestand met ongeveer 2000 records.

Elke record heeft een tekenreeks en een categorie:

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

Ik moet dit bestand inlezen in een lijst die er als volgt uitziet:

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

Hoe kan ik deze CSV importeren in de lijst die ik nodig heb met Python?


Antwoord 1, autoriteit 100%

De csv-modulegebruiken:

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

Uitvoer:

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

Als je tupels nodig hebt:

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

Uitvoer:

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

Oude Python 2-antwoord, ook met behulp van de csvmodule:

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']]

Antwoord 2, autoriteit 16%

Bijgewerkt voor Python 3:

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

Uitvoer:

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

Antwoord 3, autoriteit 13%

Pandasis redelijk goed in het omgaan met gegevens. Hier is een voorbeeld hoe het te gebruiken:

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()

Een groot voordeel is dat panda’s automatisch omgaan met koprijen.

Als je nog nooit van Seabornhebt gehoord, raad ik je aan er eens naar te kijken.

Zie ook: Hoe lees en schrijf ik CSV-bestanden met Python?

Panda’s #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')

De inhoud van df is:

    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

De inhoud van dictaten is

[{'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}]

Panda’s #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')]

De inhoud van listsis:

[['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]]

Antwoord 4, autoriteit 3%

Update voor 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)

Uitvoer:

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

Als csvfile een bestandsobject is, moet het worden geopend met newline=''.
csv-module


Antwoord 5

Als je zeker weet dat er geen komma’s in je invoer staan, behalve om de categorie te scheiden, kun je lees het bestand regel voor regelen splitsenop ,en push het resultaat naar List

Dat gezegd hebbende, het lijkt erop dat je naar een CSV-bestand kijkt, dus je zou kunnen overwegen om de moduleservoor


Antwoord 6

result = []
for line in text.splitlines():
    result.append(tuple(line.split(",")))

Antwoord 7

Een eenvoudige lus zou voldoende zijn:

lines = []
with open('test.txt', 'r') as f:
    for line in f.readlines():
        l,name = line.strip().split(',')
        lines.append((l,name))
print lines

Antwoord 8

Zoals al gezegd in de opmerkingen, kun je de csv-bibliotheek in python gebruiken. csv betekent door komma’s gescheiden waarden, wat precies het geval lijkt: een label en een waarde gescheiden door een komma.

Als categorie- en waardetype zou ik liever een woordenboektype gebruiken in plaats van een lijst met tupels.

Hoe dan ook, in de onderstaande code laat ik beide manieren zien: dis het woordenboek en lis de lijst met tupels.

import csv
file_name = "test.txt"
try:
    csvfile = open(file_name, 'rt')
except:
    print("File not found")
csvReader = csv.reader(csvfile, delimiter=",")
d = dict()
l =  list()
for row in csvReader:
    d[row[1]] = row[0]
    l.append((row[0], row[1]))
print(d)
print(l)

Antwoord 9

Helaas vind ik geen van de bestaande antwoorden bijzonder bevredigend.

Hier is een eenvoudige en complete Python 3-oplossing, met behulp van de csvmodule.

import csv
with open('../resources/temp_in.csv', newline='') as f:
    reader = csv.reader(f, skipinitialspace=True)
    rows = list(reader)
print(rows)

Let op het argument skipinitialspace=True. Dit is nodig omdat de CSV van OP helaas witruimte bevat na elke komma.

Uitvoer:

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

Antwoord 10

U kunt de functie list()gebruiken om het csv-lezerobject naar lijst te converteren

import csv
with open('input.csv') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    rows = list(reader)
    print(rows)

Antwoord 11

Als je je vereisten een beetje uitbreidt en ervan uitgaat dat de volgorde van regels je niet interesseert en je ze onder categorieën wilt groeperen, kan de volgende oplossing voor jou werken:

>>> fname = "lines.txt"
>>> from collections import defaultdict
>>> dct = defaultdict(list)
>>> with open(fname) as f:
...     for line in f:
...         text, cat = line.rstrip("\n").split(",", 1)
...         dct[cat].append(text)
...
>>> dct
defaultdict(<type 'list'>, {' CatA': ['This is the first line', 'This is the another line'], ' CatC': ['This is the third line'], ' CatB': ['This is the second line', 'This is the last line']})

Op deze manier krijg je alle relevante regels beschikbaar in het woordenboek onder de sleutel die de categorie is.


Antwoord 12

Dit is de gemakkelijkste manier in Python 3.x om een ​​CSV naar een multidimensionale array te importeren, en het zijn slechts 4 regels code zonder iets te importeren!

#pull a CSV into a multidimensional array in 4 lines!
L=[]                            #Create an empty list for the main array
for line in open('log.txt'):    #Open the file and read all the lines
    x=line.rstrip()             #Strip the \n from each line
    L.append(x.split(','))      #Split each line into a list and add it to the
                                #Multidimensional array
print(L)

Antwoord 13

Het volgende is een stukje code dat de csv-module gebruikt, maar de inhoud van file.csv extraheert naar een lijst met dicts met behulp van de eerste regel die een header is van de csv-tabel

import csv
def csv2dicts(filename):
  with open(filename, 'rb') as f:
    reader = csv.reader(f)
    lines = list(reader)
    if len(lines) < 2: return None
    names = lines[0]
    if len(names) < 1: return None
    dicts = []
    for values in lines[1:]:
      if len(values) != len(names): return None
      d = {}
      for i,_ in enumerate(names):
        d[names[i]] = values[i]
      dicts.append(d)
    return dicts
  return None
if __name__ == '__main__':
  your_list = csv2dicts('file.csv')
  print your_list

LEAVE A REPLY

Please enter your comment!
Please enter your name here

two × 3 =

Other episodes