Python importiert CSV in die Liste

Lesezeit: 6 Minuten

Benutzer-Avatar
MorganTN

Ich habe eine CSV-Datei mit etwa 2000 Datensätzen.

Jeder Datensatz hat eine Zeichenfolge und eine Kategorie:

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

Ich muss diese Datei in eine Liste einlesen, die so aussieht:

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

Wie kann ich diese CSV-Datei mit Python in die Liste importieren, die ich benötige?

  • Dann benutze csv Modul: docs.python.org/2/library/csv.html

    – Furas

    9. Juli 2014 um 19:53 Uhr


  • Wenn es eine Antwort gibt, die zu Ihrer Frage passt, akzeptieren Sie sie bitte.

    – Maciej Gol

    24. März 2015 um 21:37 Uhr

  • Mögliches Duplikat von Wie lese und schreibe ich CSV-Dateien mit Python?

    – Martin Thoma

    11. Januar 2017 um 7:47 Uhr

Benutzer-Avatar
Maciej Gol

Verwendung der csv-Modul:

import csv

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

print(data)

Ausgabe:

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

Wenn Sie Tupel benötigen:

import csv

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

print(data)

Ausgabe:

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

Alte Python 2-Antwort, die auch die verwendet csv Modul:

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

  • Warum verwenden Sie ‘rb’ anstelle von ‘r’?

    – imrek

    21. Mai 2015 um 14:28 Uhr

  • @Betrunkener Meister, b bewirkt, dass die Datei im Binärmodus und nicht im Textmodus geöffnet wird. Auf manchen Systemen bedeutet das Textmodus \n wird beim Lesen oder Schreiben in einen plattformspezifischen Zeilenumbruch konvertiert. Siehe Dokumente.

    – Maciej Gol

    24. Mai 2015 um 8:12 Uhr

  • Dies funktioniert nicht in Python 3.x: “csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)” Siehe unten für die Antwort, die in Python 3.x funktioniert

    – Gilbert

    30. Mai 2016 um 18:12 Uhr


  • Um beim Debuggen ein paar Sekunden Zeit zu sparen, sollten Sie wahrscheinlich eine Notiz für die erste Lösung hinzufügen, z. B. “Python 2.x-Version”.

    – Paradies

    30. Januar 2017 um 9:03 Uhr


  • Wie verwenden Sie Ihre erste Lösung, aber nur mit einigen Spalten aus der CSV-Datei?

    – Siguru

    6. Mai 2017 um 3:13 Uhr

Benutzer-Avatar
seokhoonlee

Aktualisiert für Python 3:

import csv

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

print(your_list)

Ausgabe:

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

  • Angabe 'r' ist der Standardmodus, daher ist es nicht erforderlich, ihn anzugeben. Die Dokumente erwähnen auch Wenn csvfile ein Dateiobjekt ist, sollte es mit newline=” geöffnet werden.

    – AMC

    6. Januar 2020 um 1:40 Uhr

Benutzer-Avatar
Martin Thomas

Pandas ist ziemlich gut im Umgang mit Daten. Hier ist ein Beispiel, wie man es verwendet:

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

Ein großer Vorteil ist, dass Pandas automatisch mit Kopfzeilen umgeht.

Falls Sie noch nichts davon gehört haben Seegeborenempfehle ich einen Blick darauf.

Siehe auch: Wie lese und schreibe ich CSV-Dateien mit Python?

Pandas Nr. 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')

Der Inhalt von df ist:

     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

Der Inhalt von Diktaten ist

[{'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 Nr. 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')]

Der Inhalt von lists ist:

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

  • tuples = [tuple(x) for x in df.values] kann geschrieben werden tuples = list(df.itertuples(index=False)) stattdessen. Beachten Sie, dass die Pandas-Dokumentation von der Verwendung von abrät .values zugunsten von .to_numpy(). Das dritte Beispiel ist für mich verwirrend. Erstens, weil die Variable benannt ist tuples, was implizieren würde, dass es sich um eine Liste von Tupeln handelt, obwohl es sich tatsächlich um eine Liste von Listen handelt. Zweitens, weil, soweit ich das beurteilen kann, der gesamte Ausdruck durch ersetzt werden kann df.to_list(). Ich weiß auch nicht, ob das zweite Beispiel hier wirklich relevant ist.

    – AMC

    6. Januar 2020 um 2:05 Uhr

Benutzer-Avatar
AbstProcDo

Update für 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)

Ausgabe:

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

Wenn csvfile ein Dateiobjekt ist, sollte es mit geöffnet werden newline="".
csv-Modul

Benutzer-Avatar
Miquel

Wenn Sie sicher sind, dass Ihre Eingabe keine Kommas enthält, außer um die Kategorie zu trennen, können Sie die Datei Zeile für Zeile lesen und Teilt an ,und verschieben Sie dann das Ergebnis auf List

Das heißt, es sieht so aus, als würden Sie sich eine CSV-Datei ansehen, also sollten Sie die Verwendung in Betracht ziehen die Module dafür

Benutzer-Avatar
Acid_Snake

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

Benutzer-Avatar
Pedro Contipelli

Du kannst den … benutzen list() Funktion zum Konvertieren des CSV-Reader-Objekts in eine Liste

import csv

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

1054500cookie-checkPython importiert CSV in die Liste

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy