Lesen Sie Dateien in Python

Dateien befinden sich überall: auf Computern, mobilen Geräten und über die Cloud. Das Arbeiten mit Dateien ist für jeden Programmierer unerlässlich, unabhängig davon, welche Programmiersprache Sie verwenden.

Die Dateibehandlung ist ein Mechanismus zum Erstellen einer Datei, zum Schreiben von Daten und zum Lesen von Daten daraus. Die gute Nachricht ist, dass Python mit Paketen für die Behandlung verschiedener Dateitypen angereichert ist.

In diesem Tutorial lernen wir, wie Sie Dateien verschiedener Typen umgehen. Wir werden uns jedoch mehr konzentrieren Lesen von Dateien mit Python.

Nachdem Sie dieses Tutorial fertiggestellt haben, wissen Sie, wie Sie Folgendes machen:

  • Öffnen Sie Dateien direkt
  • Öffnen Sie Dateien mit dem with Kontextmanager
  • Arbeiten mit Dateimodi in Python
  • Textual content lesen
  • Lesen Sie CSV -Dateien
  • Lesen Sie JSON -Dateien

Lassen Sie uns eintauchen.

Öffnen einer Datei

Vor dem Zugriff auf den Inhalt einer Datei müssen wir die Datei öffnen. Python bietet eine integrierte Funktion, mit der wir Dateien in verschiedenen Modi öffnen können. Der open() Die Funktion akzeptiert zwei wesentliche Parameter: den Dateinamen und den Modus; Der Standardmodus ist 'r'was die Datei nur zum Lesen öffnet. Die Modi definieren, wie wir auf eine Datei zugreifen können und wie wir ihren Inhalt manipulieren können. Der open() Die Funktion bietet einige verschiedene Modi, die wir später in diesem Tutorial diskutieren werden.

Versuchen wir zunächst die Funktion, indem wir eine Textdatei öffnen. Laden Sie die herunter Textdatei enthalten den Zen von Python und speichern Sie es auf dem gleichen Weg wie Ihr Code.

f = open('zen_of_python.txt', 'r')
print(f.learn())
f.shut()
    The Zen of Python, by Tim Peters

    Lovely is healthier than ugly.
    Express is healthier than implicit.
    Easy is healthier than complicated.
    Advanced is healthier than difficult.
    Flat is healthier than nested.
    Sparse is healthier than dense.
    Readability counts.
    Particular instances aren't particular sufficient to interrupt the principles.
    Though practicality beats purity.
    Errors ought to by no means cross silently.
    Except explicitly silenced.
    Within the face of ambiguity, refuse the temptation to guess.
    There ought to be one-- and ideally just one --obvious method to do it.
    Though that means is probably not apparent at first except you are Dutch.
    Now's higher than by no means.
    Though by no means is commonly higher than *proper* now.
    If the implementation is difficult to clarify, it is a dangerous thought.
    If the implementation is straightforward to clarify, it might be a good suggestion.
    Namespaces are one honking nice thought -- let's do extra of these!

Im obigen Code die open() Die Funktion öffnet die Textdatei im Lesemodus, sodass wir Informationen aus der Datei abrufen können, ohne sie versehentlich zu ändern. In der ersten Zeile die Ausgabe der open() Funktion wird dem zugeordnet f Variable, ein Objekt, das die Textdatei darstellt. In der zweiten Zeile des obigen Codes verwenden wir die learn() Methode zum Lesen der gesamten Datei und zum Drucken des Inhalts. Der shut() Die Methode schließt die Datei in der letzten Zeile. Wir müssen die geöffneten Dateien immer schließen, nachdem wir mit ihnen fertig sind, um unsere Computerressourcen zu veröffentlichen und keine Ausnahmen zu erhöhen.

Eine bessere Möglichkeit, Dateien in Python zu lesen

In Python können wir das verwenden with Kontextmanager Um sicherzustellen, dass ein Programm die nach Abschluss der Datei verwendeten Ressourcen veröffentlicht, auch wenn eine Ausnahme aufgetreten ist. Versuchen wir es:

with open('zen_of_python.txt') as f:
    print(f.learn())
    The Zen of Python, by Tim Peters

    Lovely is healthier than ugly.
    Express is healthier than implicit.
    Easy is healthier than complicated.
    Advanced is healthier than difficult.
    Flat is healthier than nested.
    Sparse is healthier than dense.
    Readability counts.
    Particular instances aren't particular sufficient to interrupt the principles.
    Though practicality beats purity.
    Errors ought to by no means cross silently.
    Except explicitly silenced.
    Within the face of ambiguity, refuse the temptation to guess.
    There ought to be one-- and ideally just one --obvious method to do it.
    Though that means is probably not apparent at first except you are Dutch.
    Now's higher than by no means.
    Though by no means is commonly higher than *proper* now.
    If the implementation is difficult to clarify, it is a dangerous thought.
    If the implementation is straightforward to clarify, it might be a good suggestion.
    Namespaces are one honking nice thought -- let's do extra of these!

Der obige Code erstellt einen Kontext mit dem with Anweisung, dass das Dateiobjekt nicht mehr aus dem Kontext geöffnet ist. Die gebundene Variable, frepräsentiert das Dateiobjekt, dass alle Dateiobjektmethoden über die Variable zugegriffen werden. Der learn() Die Methode liest die gesamte Datei in der zweiten Zeile und dann die print() Die Funktion gibt den Dateiinhalt aus.

Wenn das Programm das Ende der erreicht with Anweisungsblockkontext schließt die Datei zur Veröffentlichung der Ressourcen und stellt sicher, dass andere Programme sie verwenden können. Im Allgemeinen die Verwendung der with Die Erklärung ist eine sehr empfohlene Praxis, wenn Sie mit Objekten arbeiten, die geschlossen werden müssen, sobald sie nicht mehr benötigt werden, z. B. Dateien, Datenbanken und Netzwerkverbindungen.

Beachten Sie, dass wir Zugriff auf die haben f variabel auch nach dem Verlassen der with Kontext -Supervisor -Block; Die Datei ist jedoch geschlossen. Versuchen wir einige der Dateiobjekteigenschaften, um festzustellen, ob die Variable noch lebendig und zugänglich ist:

print("Filename is '{}'.".format(f.title))
if f.closed:
    print("File is closed.")
else:
    print("File is not closed.")
    Filename is 'zen_of_python.txt'.
    File is closed.

Es ist jedoch unmöglich, aus der Datei zu lesen oder in die Datei zu schreiben. Wenn eine Datei geschlossen ist, führt jeder Versuch, auf ihren Inhalt zuzugreifen, zu dem folgenden Fehler:

f.learn()
    ---------------------------------------------------------------------------

    ValueError                                Traceback (most up-to-date name final)

    ~AppDataLocalTemp/ipykernel_9828/3059900045.py in <module>
    ----> 1 f.learn()

    ValueError: I/O operation on closed file.

Arbeiten mit Dateimodi in Python

Wenn Sie mit den integrierten Dateien in Python arbeiten open() Funktion müssen Sie einen Modus angeben. Dies zeigt Python genau, was Sie mit der Datei vorhaben – ob Sie Informationen daraus lesen, neue Informationen schreiben, vorhandenen Inhalten hinzufügen und vieles mehr. Es wird auch festgelegt, ob die Datei als einfacher Textual content oder als Rohdaten (wie ein Bild) behandelt werden sollte. Hier ist ein Blick auf die Hauptdateimodi:

Modus Beschreibung
'r' Öffnet eine Datei für Lektüre (Dies ist die Standardeinstellung, wenn Sie keinen Modus angeben). Dies führt zu einem Fehler, wenn die Datei nicht vorhanden ist. Python beginnt vom Beginn der Datei zu lesen.
'w' Öffnet eine Datei für Schreiben. Wenn die Datei bereits vorhanden ist, wird der gesamte Inhalt zuerst gelöscht. Wenn die Datei nicht vorhanden ist, wird eine neue erstellt.
'a' Öffnet eine Datei für angehängt. Neue Daten werden am Ende der Datei hinzugefügt. Wenn die Datei nicht vorhanden ist, wird sie erstellt. Python wird am Ende der Datei schreiben.
'x' Öffnet eine Datei für exklusive Kreation. Es wird eine neue Datei erstellt, aber wenn eine Datei mit diesem Namen bereits vorhanden ist, wird ein Fehler verursacht.

Über diese grundlegenden Modi hinaus können Sie Python auch mitteilen, wie der Inhalt der Datei umgegangen wird:

  • 't': Textmodus (Dies ist der Normal). Python behandelt den Dateiinhalt als Zeichenfolgen und behandelt automatisch Dinge wie Zeilenende und Charaktercodierung (normalerweise verwendet der Standardeinsatz Ihres Techniques). Additionally nur benutze 'r' ist dasselbe wie die Verwendung 'rt'.
  • 'b': Binärmodus. Python behandelt den Dateiinhalt als Roh -Bytes. Dies ist wichtig für die Arbeit mit Nicht-Textdateien wie Bildern, Audiodateien oder Daten, bei denen Sie eine genaue Steuerung über die Bytes benötigen.

Sie können auch die primären Modi kombinieren ('r'Anwesend 'w'Anwesend 'a'Anwesend 'x') mit '+' Sowohl das Lesen als auch das Schreiben ermöglichen:

  • 'r+': Öffnet eine Datei sowohl zum Lesen als auch zum Schreiben. Der Ausgangspunkt für beide ist der Beginn der Datei und löscht den vorhandenen Inhalt nicht.
  • 'w+': Öffnet eine Datei sowohl zum Schreiben als auch zum Lesen. Wenn die Datei vorhanden ist, wird sie zuerst entleert. Wenn es nicht existiert, wird eine neue erstellt.
  • 'a+': Öffnet eine Datei sowohl für das Anhängen als auch für das Lesen. Neues Schreiben wird immer am Ende der Datei stattfinden, aber Sie können sich von jedem Punkt aus bewegen und lesen. Wenn die Datei nicht vorhanden ist, wird sie erstellt.
  • 'x+': Öffnet eine Datei für die exklusive Erstellung und ermöglicht das Lesen und Schreiben. Es wird fehlschlagen, wenn die Datei bereits vorhanden ist.

Sie können beispielsweise die Textual content-/Binärmodi mit diesen sogar kombinieren. 'rb' bedeutet in binär lesen und 'w+b' bedeutet, in binär zu lesen und zu schreiben (und zuerst die Datei zu entleeren).

Schauen wir uns das Kopieren einer Bilddatei an. dataquest_logo.png. Da Bilder nicht Textual content sind, müssen wir den Binärmodus verwenden:

source_image="dataquest_logo.png"
copied_image="data_quest_logo_copy.png"

with open(source_image, 'rb') as source_file:
  with open(copied_image, 'wb') as destination_file:
    for byte in source_file:
      destination_file.write(byte)
print(f"Efficiently copied '{source_image}' to '{copied_image}'")

Dieser Code liest die Originalbilddatei im Binärmodus ('rb') und schreibt es Byte per Byte in eine neue Datei im Binärmodus (('wb'), Erstellen einer genauen Kopie. Wir verwenden eine einfache Schleife, um jedes Byte im Unique zu durchlaufen und in die neue Datei zu schreiben.

Textdateien lesen

Nachdem wir nun ein gutes Verständnis der Dateimodi haben, konzentrieren wir uns speziell auf das Lesen des Inhalts von Textdateien. Der nächste Teil umfasst einige nützliche Methoden, um genau das zu tun.

Bisher haben wir gelernt, dass der gesamte Inhalt einer Datei mit dem gelesen werden kann learn() Verfahren. Was ist, wenn wir nur ein paar Bytes aus einer Textdatei lesen möchten? Geben Sie dazu die Anzahl der Bytes in der an learn() Verfahren. Versuchen wir es:

with open('zen_of_python.txt') as f:
    print(f.learn(17))
The Zen of Python

Der einfache Code oben liest die ersten 17 Bytes der zen_of_python.txt Datei und druckt sie aus.

Manchmal ist es sinnvoller, den Inhalt einer Textdatei jeweils eine Zeile zu lesen. In diesem Fall können wir die verwenden readline() Verfahren. Lass es uns tun:

with open('zen_of_python.txt') as f:
    print(f.readline())
The Zen of Python, by Tim Peters

Der obige Code gibt die erste Zeile der Datei zurück. Wenn wir die Methode noch einmal aufrufen, wird die zweite Zeile in der Datei usw. wie folgt zurückgegeben:

with open('zen_of_python.txt') as f:
    print(f.readline())
    print(f.readline())
    print(f.readline())
    print(f.readline())
The Zen of Python, by Tim Peters  

Lovely is healthier than ugly.

Express is healthier than implicit.

Diese nützliche Methode hilft uns, die gesamte Datei schrittweise zu lesen. Der folgende Code gibt die gesamte Datei aus, indem er über die Zeile nach Zeile iteriert, bis der Dateizeiger, der verfolgt, wo wir lesen oder die Datei schreiben, das Ende der Datei erreicht. Wenn die readline() Die Methode erreicht das Ende der Datei, sie gibt eine leere Zeichenfolge zurück. ''.With Open (‚zen_of_python.txt‘) als f:

with open('zen_of_python.txt') as f:
    line = f.readline()
    whereas line:
        print(line, finish='')
        line = f.readline()        
    The Zen of Python, by Tim Peters

    Lovely is healthier than ugly.
    Express is healthier than implicit.
    Easy is healthier than complicated.
    Advanced is healthier than difficult.
    Flat is healthier than nested.
    Sparse is healthier than dense.
    Readability counts.
    Particular instances aren't particular sufficient to interrupt the principles.
    Though practicality beats purity.
    Errors ought to by no means cross silently.
    Except explicitly silenced.
    Within the face of ambiguity, refuse the temptation to guess.
    There ought to be one-- and ideally just one --obvious method to do it.
    Though that means is probably not apparent at first except you are Dutch.
    Now's higher than by no means.
    Though by no means is commonly higher than *proper* now.
    If the implementation is difficult to clarify, it is a dangerous thought.
    If the implementation is straightforward to clarify, it might be a good suggestion.
    Namespaces are one honking nice thought -- let's do extra of these!

Der obige Code liest die erste Zeile der Datei außerhalb der whereas -Schleife und weist ihn dem zu line Variable. Im Inneren der whereas -Schleife druckt es die in der gespeicherte Zeichenfolge line Variable, liest dann die nächste Zeile der Datei. Die whereas -Schleife iteriert den Prozess bis zum readline() Die Methode gibt eine leere Zeichenfolge zurück. Die leere Zeichenfolge bewertet sich an False In der whereas -Schleife endet der Iterationsprozess.

Die andere hilfreiche Methode zum Lesen von Textdateien ist die readlines() Verfahren. Das Anwenden dieser Methode auf ein Dateiobjekt gibt eine Liste von Zeichenfolgen zurück, die jede Zeile der Datei enthalten. Mal sehen, wie es funktioniert:

with open('zen_of_python.txt') as f:
    traces = f.readlines()

Überprüfen wir den Datentyp der traces Variable und drucken Sie es dann:

print(sort(traces))
print(traces)
<class 'listing'>
('The Zen of Python, by Tim Petersn', 'n', 'Lovely is healthier than ugly.n', 'Express is healthier than implicit.n', 'Easy is healthier than complicated.n', 'Advanced is healthier than difficult.n', 'Flat is healthier than nested.n', 'Sparse is healthier than dense.n', 'Readability counts.n', "Particular instances aren't particular sufficient to interrupt the principles.n", 'Though practicality beats purity.n', 'Errors ought to by no means cross silently.n', 'Except explicitly silenced.n', 'Within the face of ambiguity, refuse the temptation to guess.n', 'There ought to be one-- and ideally just one --obvious method to do it.n', "Though that means is probably not apparent at first except you are Dutch.n", 'Now's higher than by no means.n', 'Though by no means is commonly higher than *proper* now.n', "If the implementation is difficult to clarify, it is a dangerous thought.n", 'If the implementation is straightforward to clarify, it might be a good suggestion.n', "Namespaces are one honking nice thought -- let's do extra of these!")

Es handelt sich um eine Liste von Zeichenfolgen, in denen jedes Factor in der Liste eine Zeile der Textdatei ist. Der n Escape -Zeichen repräsentiert eine neue Zeile in der Datei. Außerdem können wir auf jedes Factor in der Liste zugreifen, indem wir Vorgänge indexieren oder schneiden:

print(traces)
print(traces(3:5))
print(traces(-1))
('The Zen of Python, by Tim Petersn', 'n', 'Lovely is healthier than ugly.n', 'Express is healthier than implicit.n', 'Easy is healthier than complicated.n', 'Advanced is healthier than difficult.n', 'Flat is healthier than nested.n', 'Sparse is healthier than dense.n', 'Readability counts.n', "Particular instances aren't particular sufficient to interrupt the principles.n", 'Though practicality beats purity.n', 'Errors ought to by no means cross silently.n', 'Except explicitly silenced.n', 'Within the face of ambiguity, refuse the temptation to guess.n', 'There ought to be one-- and ideally just one --obvious method to do it.n', "Though that means is probably not apparent at first except you are Dutch.n", 'Now's higher than by no means.n', 'Though by no means is commonly higher than *proper* now.n', "If the implementation is difficult to clarify, it is a dangerous thought.n", 'If the implementation is straightforward to clarify, it might be a good suggestion.n', "Namespaces are one honking nice thought -- let's do extra of these!")
('Express is healthier than implicit.n', 'Easy is healthier than complicated.n')
Namespaces are one honking nice thought -- let's do extra of these!

Lesen von CSV -Dateien

Bisher haben wir gelernt, wie man mit regulären Textdateien arbeitet. Manchmal werden jedoch Daten in einem CSV -Format geliefert, und es ist für Datenfachleute üblich, die erforderlichen Informationen abzurufen und den Inhalt von CSV -Dateien zu manipulieren.

Wir werden das CSV -Modul in diesem Abschnitt verwenden. Das CSV-Modul bietet hilfreiche Methoden zum Lesen der in einer CSV-Datei gespeicherten von Kommas getrennten Werte. Wir werden es jetzt versuchen, aber zuerst müssen Sie die herunterladen chocolate.csv Datei und speichern Sie es im aktuellen Arbeitsverzeichnis:

import csv

with open('chocolate.csv') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        print(row)
    ('Firm', 'Bean Origin or Bar Identify', 'REF', 'Evaluation Date', 'Cocoa P.c', 'Firm Location', 'Ranking', 'Bean Sort', 'Nation of Origin')
    ('A. Morin', 'Agua Grande', '1876', '2016', '63%', 'France', '3.75', 'Âxa0', 'Sao Tome')
    ('A. Morin', 'Kpime', '1676', '2015', '70%', 'France', '2.75', 'Âxa0', 'Togo')
    ('A. Morin', 'Atsane', '1676', '2015', '70%', 'France', '3', 'Âxa0', 'Togo')
    ('A. Morin', 'Akata', '1680', '2015', '70%', 'France', '3.5', 'Âxa0', 'Togo')
    ('Acalli', 'Chulucanas, El Platanal', '1462', '2015', '70%', 'U.S.A.', '3.75', 'Âxa0', 'Peru')
    ('Acalli', 'Tumbes, Norandino', '1470', '2015', '70%', 'U.S.A.', '3.75', 'Criollo', 'Peru')
    ('Adi', 'Vanua Levu', '705', '2011', '60%', 'Fiji', '2.75', 'Trinitario', 'Fiji')
    ('Adi', 'Vanua Levu, Toto-A', '705', '2011', '80%', 'Fiji', '3.25', 'Trinitario', 'Fiji')
    ('Adi', 'Vanua Levu', '705', '2011', '88%', 'Fiji', '3.5', 'Trinitario', 'Fiji')
    ('Adi', 'Vanua Levu, Ami-Ami-CA', '705', '2011', '72%', 'Fiji', '3.5', 'Trinitario', 'Fiji')
    ('Aequare (Gianduja)', 'Los Rios, Quevedo, Arriba', '370', '2009', '55%', 'Ecuador', '2.75', 'Forastero (Arriba)', 'Ecuador')
    ('Aequare (Gianduja)', 'Los Rios, Quevedo, Arriba', '370', '2009', '70%', 'Ecuador', '3', 'Forastero (Arriba)', 'Ecuador')
    ('Ah Cacao', 'Tabasco', '316', '2009', '70%', 'Mexico', '3', 'Criollo', 'Mexico')
    ("Akesson's (Pralus)", 'Bali (west), Sukrama Household, Melaya space', '636', '2011', '75%', 'Switzerland', '3.75', 'Trinitario', 'Indonesia')
    ("Akesson's (Pralus)", 'Madagascar, Ambolikapiky P.', '502', '2010', '75%', 'Switzerland', '2.75', 'Criollo', 'Madagascar')
    ("Akesson's (Pralus)", 'Monte Alegre, D. Badero', '508', '2010', '75%', 'Switzerland', '2.75', 'Forastero', 'Brazil')
    ('Alain Ducasse', 'Trinite', '1215', '2014', '65%', 'France', '2.75', 'Trinitario', 'Trinidad')
    ('Alain Ducasse', 'Vietnam', '1215', '2014', '75%', 'France', '2.75', 'Trinitario', 'Vietnam')
    ('Alain Ducasse', 'Madagascar', '1215', '2014', '75%', 'France', '3', 'Trinitario', 'Madagascar')
    ('Alain Ducasse', 'Chuao', '1061', '2013', '75%', 'France', '2.5', 'Trinitario', 'Venezuela')
    ('Alain Ducasse', 'Piura, Perou', '1173', '2013', '75%', 'France', '2.5', 'Âxa0', 'Peru')
    ('Alexandre', 'Winak Coop, Napo', '1944', '2017', '70%', 'Netherlands', '3.5', 'Forastero (Nacional)', 'Ecuador')
    ('Alexandre', 'La Dalia, Matagalpa', '1944', '2017', '70%', 'Netherlands', '3.5', 'Criollo, Trinitario', 'Nicaragua')
    ('Alexandre', 'Tien Giang', '1944', '2017', '70%', 'Netherlands', '3.5', 'Trinitario', 'Vietnam')
    ('Alexandre', 'Makwale Village, Kyela', '1944', '2017', '70%', 'Netherlands', '3.5', 'Forastero', 'Tanzania')
    ('Altus aka Cao Artisan', 'Momotombo', '1728', '2016', '60%', 'U.S.A.', '2.75', 'Âxa0', 'Nicaragua')
    ('Altus aka Cao Artisan', 'Bolivia', '1133', '2013', '60%', 'U.S.A.', '3', 'Âxa0', 'Bolivia')
    ('Altus aka Cao Artisan', 'Peru', '1133', '2013', '60%', 'U.S.A.', '3.25', 'Âxa0', 'Peru')
    ('Amano', 'Morobe', '725', '2011', '70%', 'U.S.A.', '4', 'Âxa0', 'Papua New Guinea')
    ('Amano', 'Dos Rios', '470', '2010', '70%', 'U.S.A.', '3.75', 'Âxa0', 'Dominican Republic')
    ('Amano', 'Guayas', '470', '2010', '70%', 'U.S.A.', '4', 'Âxa0', 'Ecuador')
    ('Amano', 'Chuao', '544', '2010', '70%', 'U.S.A.', '3', 'Trinitario', 'Venezuela')
    ('Amano', 'Montanya', '363', '2009', '70%', 'U.S.A.', '3', 'Âxa0', 'Venezuela')
    ('Amano', 'Bali, Jembrana', '304', '2008', '70%', 'U.S.A.', '2.75', 'Âxa0', 'Indonesia')
    ('Amano', 'Madagascar', '129', '2007', '70%', 'U.S.A.', '3.5', 'Trinitario', 'Madagascar')
    ('Amano', 'Cuyagua', '147', '2007', '70%', 'U.S.A.', '3', 'Âxa0', 'Venezuela')
    ('Amano', 'Ocumare', '175', '2007', '70%', 'U.S.A.', '3.75', 'Criollo', 'Venezuela')
    ('Amatller (Simon Coll)', 'Ghana', '322', '2009', '70%', 'Spain', '3', 'Forastero', 'Ghana')
    ('Amatller (Simon Coll)', 'Ecuador', '327', '2009', '70%', 'Spain', '2.75', 'Âxa0', 'Ecuador')
    ('Amatller (Simon Coll)', 'Ecuador', '464', '2009', '85%', 'Spain', '2.75', 'Âxa0', 'Ecuador')
    ('Amatller (Simon Coll)', 'Ghana', '464', '2009', '85%', 'Spain', '3', 'Forastero', 'Ghana')
    ('Amazona', 'LamasdelChanka, San Martin, Oro Verde coop', '1145', '2013', '72%', 'Peru', '3.25', 'Âxa0', 'Peru')
    ('Ambrosia', 'Venezuela', '1498', '2015', '70%', 'Canada', '3.25', 'Âxa0', 'Venezuela')
    ('Ambrosia', 'Peru', '1498', '2015', '68%', 'Canada', '3.5', 'Âxa0', 'Peru')
    ('Amedei', 'Piura, Blanco de Criollo', '979', '2012', '70%', 'Italy', '3.75', 'Âxa0', 'Peru')
    ('Amedei', 'Porcelana', '111', '2007', '70%', 'Italy', '4', 'Criollo (Porcelana)', 'Venezuela')
    ('Amedei', '9', '111', '2007', '75%', 'Italy', '4', 'Mix', 'Âxa0')
    ('Amedei', 'Chuao', '111', '2007', '70%', 'Italy', '5', 'Trinitario', 'Venezuela')
    ('Amedei', 'Ecuador', '123', '2007', '70%', 'Italy', '3', 'Trinitario', 'Ecuador')
    ('Amedei', 'Jamaica', '123', '2007', '70%', 'Italy', '3', 'Trinitario', 'Jamaica')
    ('Amedei', 'Grenada', '123', '2007', '70%', 'Italy', '3.5', 'Trinitario', 'Grenada')
    ('Amedei', 'Venezuela', '123', '2007', '70%', 'Italy', '3.75', 'Trinitario (85% Criollo)', 'Venezuela')
    ('Amedei', 'Madagascar', '123', '2007', '70%', 'Italy', '4', 'Trinitario (85% Criollo)', 'Madagascar')
    ('Amedei', 'Trinidad', '129', '2007', '70%', 'Italy', '3.5', 'Trinitario', 'Trinidad')
    ('Amedei', 'Toscano Black', '170', '2007', '63%', 'Italy', '3.5', 'Mix', 'Âxa0')
    ('Amedei', 'Toscano Black', '40', '2006', '70%', 'Italy', '5', 'Mix', 'Âxa0')
    ('Amedei', 'Toscano Black', '75', '2006', '66%', 'Italy', '4', 'Mix', 'Âxa0')
    ('AMMA', 'Catongo', '1065', '2013', '75%', 'Brazil', '3.25', 'Forastero (Catongo)', 'Brazil')
    ('AMMA', 'Monte Alegre, 3 diff. plantations', '572', '2010', '85%', 'Brazil', '2.75', 'Forastero (Parazinho)', 'Brazil')
    ('AMMA', 'Monte Alegre, 3 diff. plantations', '572', '2010', '50%', 'Brazil', '3.75', 'Forastero (Parazinho)', 'Brazil')
    ('AMMA', 'Monte Alegre, 3 diff. plantations', '572', '2010', '75%', 'Brazil', '3.75', 'Forastero (Parazinho)', 'Brazil')
    ('AMMA', 'Monte Alegre, 3 diff. plantations', '572', '2010', '60%', 'Brazil', '4', 'Forastero (Parazinho)', 'Brazil')
    ('Anahata', 'Elvesia', '1259', '2014', '75%', 'U.S.A.', '3', 'Âxa0', 'Dominican Republic')
    ('Animas', 'Alto Beni', '1852', '2016', '75%', 'U.S.A.', '3.5', 'Âxa0', 'Bolivia')
    ('Ara', 'Madagascar', '1375', '2014', '75%', 'France', '3', 'Trinitario', 'Madagascar')
    ('Ara', 'Chiapas', '1379', '2014', '72%', 'France', '2.5', 'Âxa0', 'Mexico')
    ('Arete', 'Camino Verde', '1602', '2015', '75%', 'U.S.A.', '3.5', 'Âxa0', 'Ecuador')
    ('Artisan du Chocolat', 'Congo', '300', '2008', '72%', 'U.Okay.', '3.75', 'Forastero', 'Congo')
    ('Artisan du Chocolat (Casa Luker)', 'Orinoqua Area, Arauca', '1181', '2013', '72%', 'U.Okay.', '2.75', 'Trinitario', 'Colombia')
    ('Askinosie', 'Mababa', '1780', '2016', '68%', 'U.S.A.', '3.75', 'Trinitario', 'Tanzania')
    ('Askinosie', 'Tenende, Uwate', '647', '2011', '72%', 'U.S.A.', '3.75', 'Trinitario', 'Tanzania')
    ('Askinosie', 'Cortes', '661', '2011', '70%', 'U.S.A.', '3.75', 'Trinitario', 'Honduras')
    ('Askinosie', 'Davao', '331', '2009', '77%', 'U.S.A.', '3.75', 'Trinitario', 'Philippines')
    ('Askinosie', 'Xoconusco', '141', '2007', '75%', 'U.S.A.', '2.5', 'Trinitario', 'Mexico')
    ('Askinosie', 'San Jose del Tambo', '175', '2007', '70%', 'U.S.A.', '3', 'Forastero (Arriba)', 'Ecuador')
    ('Bahen & Co.', 'Houseblend', '999', '2012', '70%', 'Australia', '2.5', 'Mix', 'Âxa0')
    ('Bakau', 'Bambamarca, 2015', '1454', '2015', '70%', 'Peru', '2.75', 'Âxa0', 'Peru')
    ('Bakau', 'Huallabamba, 2015', '1454', '2015', '70%', 'Peru', '3.5', 'Âxa0', 'Peru')
    ('Bar Au Chocolat', 'Bahia', '1554', '2015', '70%', 'U.S.A.', '3.5', 'Âxa0', 'Brazil')
    ('Bar Au Chocolat', 'Maranon Canyon', '1295', '2014', '70%', 'U.S.A.', '4', 'Forastero (Nacional)', 'Peru')
    ('Bar Au Chocolat', 'Duarte Province', '983', '2012', '70%', 'U.S.A.', '3.25', 'Âxa0', 'Dominican Republic')
    ('Bar Au Chocolat', 'Chiapas', '983', '2012', '70%', 'U.S.A.', '3.5', 'Âxa0', 'Mexico')
    ('Bar Au Chocolat', 'Sambirano', '983', '2012', '70%', 'U.S.A.', '3.75', 'Trinitario', 'Madagascar')
    ("Baravelli's", 'single property', '955', '2012', '80%', 'Wales', '2.75', 'Âxa0', 'Costa Rica')
    ('Batch', 'Dominican Republic, Batch 3', '1840', '2016', '65%', 'U.S.A.', '3.5', 'Âxa0', 'Domincan Republic')
    ('Batch', 'Brazil', '1868', '2016', '70%', 'U.S.A.', '3.75', 'Âxa0', 'Brazil')
    ('Batch', 'Ecuador', '1880', '2016', '65%', 'U.S.A.', '3.25', 'Âxa0', 'Ecuador')
    ('Beau Cacao', 'Asajaya E, NW Borneo, b. #132/4500', '1948', '2017', '73%', 'U.Okay.', '3', 'Âxa0', 'Malaysia')
    ('Beau Cacao', 'Serian E., NW Borneo, b. #134/3800', '1948', '2017', '72%', 'U.Okay.', '3.25', 'Âxa0', 'Malaysia')
    ('Beehive', 'Brazil, Batch 20316', '1784', '2016', '80%', 'U.S.A.', '2.75', 'Âxa0', 'Brazil')
    ('Beehive', 'Dominican Republic, Batch 31616', '1784', '2016', '70%', 'U.S.A.', '2.75', 'Âxa0', 'Domincan Republic')
    ('Beehive', 'Ecuador, Batch 31516', '1784', '2016', '70%', 'U.S.A.', '2.75', 'Âxa0', 'Ecuador')
    ('Beehive', 'Ecuador', '1788', '2016', '90%', 'U.S.A.', '2.75', 'Âxa0', 'Ecuador')
    ('Belcolade', 'Costa Rica', '586', '2010', '64%', 'Belgium', '2.75', 'Âxa0', 'Costa Rica')
    ('Belcolade', 'Papua New Guinea', '586', '2010', '64
    ('Belcolade', 'Peru', '586', '2010', '64%', 'Belgium', '2.75', 'Âxa0', 'Peru')
    ('Belcolade', 'Ecuador', '586', '2010', '71%', 'Belgium', '3.5', 'Âxa0', 'Ecuador')
    ('Bellflower', 'Kakao Kamili, Kilombero Valley', '1800', '2016', '70%', 'U.S.A.', '3.5', 'Criollo, Trinitario', 'Tanzania')
    ('Bellflower', 'Alto Beni, Palos Blanco', '1804', '2016', '70%', 'U.S.A.', '3.25', 'Âxa0', 'Bolivia')
    ('Classic Plantations (Tulicorp)', 'Los Rios, Rancho Grande 2007', '153', '2007', '65%', 'U.S.A.', '3', 'Forastero (Arriba)', 'Ecuador')
    ('Violet Sky', 'Sambirano Valley', '1458', '2015', '77%', 'U.S.A.', '2.75', 'Trinitario', 'Madagascar')
    ('Wm', 'Wild Beniano, 2016, batch 128, Heirloom', '1912', '2016', '76%', 'U.S.A.', '3.5', 'Âxa0', 'Bolivia')
    ('Wm', 'Ghana, 2013, batch 129', '1916', '2016', '75%', 'U.S.A.', '3.75', 'Âxa0', 'Ghana')
    ('Woodblock', 'La Crimson', '769', '2011', '70%', 'U.S.A.', '3.5', 'Âxa0', 'Dominican Republic')
    ('Xocolat', 'Hispaniola', '1057', '2013', '66%', 'Domincan Republic', '3', 'Âxa0', 'Dominican Republic')
    ('Xocolla', 'Sambirano, batch 170102', '1948', '2017', '70%', 'U.S.A.', '2.75', 'Âxa0', 'Madagascar')
    ('Xocolla', 'Hispaniola, batch 170104', '1948', '2017', '70%', 'U.S.A.', '2.5', 'Âxa0', 'Dominican Republic')
    ('Zart Pralinen', 'UNOCACE', '1824', '2016', '70%', 'Austria', '2.75', 'Nacional (Arriba)', 'Ecuador')
    ('Zart Pralinen', 'San Juan Property', '1824', '2016', '85%', 'Austria', '2.75', 'Trinitario', 'Trinidad')
    ('Zokoko', 'Guadalcanal', '1716', '2016', '78%', 'Australia', '3.75', 'Âxa0', 'Solomon Islands')

Jede Zeile der CSV -Datei bildet eine Liste, in der auf jedes Factor wie folgt leicht zugegriffen werden kann:

import csv

with open('chocolate.csv') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        print("The {} firm is positioned in {}.".format(row(0), row(5)))
    The Firm firm is positioned in Firm Location.
    The A. Morin firm is positioned in France.
    The A. Morin firm is positioned in France.
    The A. Morin firm is positioned in France.
    The A. Morin firm is positioned in France.
    The Acalli firm is positioned in U.S.A..
    The Acalli firm is positioned in U.S.A..
    The Adi firm is positioned in Fiji.
    The Adi firm is positioned in Fiji.
    The Adi firm is positioned in Fiji.
    The Adi firm is positioned in Fiji.
    The Aequare (Gianduja) firm is positioned in Ecuador.
    The Aequare (Gianduja) firm is positioned in Ecuador.
    The Ah Cacao firm is positioned in Mexico.
    The Akesson's (Pralus) firm is positioned in Switzerland.
    The Akesson's (Pralus) firm is positioned in Switzerland.
    The Akesson's (Pralus) firm is positioned in Switzerland.
    The Alain Ducasse firm is positioned in France.
    The Alain Ducasse firm is positioned in France.
    The Alain Ducasse firm is positioned in France.
    The Alain Ducasse firm is positioned in France.
    The Alain Ducasse firm is positioned in France.
    The Alexandre firm is positioned in Netherlands.
    The Alexandre firm is positioned in Netherlands.
    The Alexandre firm is positioned in Netherlands.
    The Alexandre firm is positioned in Netherlands.
    The Altus aka Cao Artisan firm is positioned in U.S.A..
    The Altus aka Cao Artisan firm is positioned in U.S.A..
    The Altus aka Cao Artisan firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amatller (Simon Coll) firm is positioned in Spain.
    The Amatller (Simon Coll) firm is positioned in Spain.
    The Amatller (Simon Coll) firm is positioned in Spain.
    The Amatller (Simon Coll) firm is positioned in Spain.
    The Amazona firm is positioned in Peru.
    The Ambrosia firm is positioned in Canada.
    The Ambrosia firm is positioned in Canada.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The AMMA firm is positioned in Brazil.
    The AMMA firm is positioned in Brazil.
    The AMMA firm is positioned in Brazil.
    The AMMA firm is positioned in Brazil.
    The AMMA firm is positioned in Brazil.
    The Anahata firm is positioned in U.S.A..
    The Animas firm is positioned in U.S.A..
    The Ara firm is positioned in France.
    The Ara firm is positioned in France.
    The Arete firm is positioned in U.S.A..
    The Artisan du Chocolat firm is positioned in U.Okay..
    The Artisan du Chocolat (Casa Luker) firm is positioned in U.Okay..
    The Askinosie firm is positioned in U.S.A..
    The Askinosie firm is positioned in U.S.A..
    The Askinosie firm is positioned in U.S.A..
    The Askinosie firm is positioned in U.S.A..
    The Askinosie firm is positioned in U.S.A..
    The Askinosie firm is positioned in U.S.A..
    The Bahen & Co. firm is positioned in Australia.
    The Bakau firm is positioned in Peru.
    The Bakau firm is positioned in Peru.
    The Bar Au Chocolat firm is positioned in U.S.A..
    The Bar Au Chocolat firm is positioned in U.S.A..
    The Bar Au Chocolat firm is positioned in U.S.A..
    The Bar Au Chocolat firm is positioned in U.S.A..
    The Bar Au Chocolat firm is positioned in U.S.A..
    The Baravelli's firm is positioned in Wales.
    The Batch firm is positioned in U.S.A..
    The Batch firm is positioned in U.S.A..
    The Batch firm is positioned in U.S.A..
    The Beau Cacao firm is positioned in U.Okay..
    The Beau Cacao firm is positioned in U.Okay..
    The Beehive firm is positioned in U.S.A..
    The Beehive firm is positioned in U.S.A..
    The Beehive firm is positioned in U.S.A..
    The Beehive firm is positioned in U.S.A..
    The Belcolade firm is positioned in Belgium.
    The Belcolade firm is positioned in Belgium.
    The Belcolade firm is positioned in Belgium.
    The Belcolade firm is positioned in Belgium.
    The Bellflower firm is positioned in U.S.A..
    The Bellflower firm is positioned in U.S.A..
    The Classic Plantations (Tulicorp) firm is positioned in U.S.A..
    The Violet Sky firm is positioned in U.S.A..
    The Wm firm is positioned in U.S.A..
    The Wm firm is positioned in U.S.A..
    The Woodblock firm is positioned in U.S.A..
    The Xocolat firm is positioned in Domincan Republic.
    The Xocolla firm is positioned in U.S.A..
    The Xocolla firm is positioned in U.S.A..
    The Zart Pralinen firm is positioned in Austria.
    The Zart Pralinen firm is positioned in Austria.
    The Zokoko firm is positioned in Australia.

Es ist möglich, den Namen der Spalten zu verwenden, anstatt ihre Indizes zu verwenden, was für Entwickler normalerweise bequemer ist. In diesem Fall anstatt die zu verwenden reader() Methode verwenden wir die DictReader() Methode, die eine Sammlung von Wörterbuchobjekten zurückgibt. Versuchen wir es:

import csv

with open('chocolate.csv') as f:
    dict_reader = csv.DictReader(f, delimiter=',')
    for row in dict_reader:
        print("The {} firm is positioned in {}.".format(row('Firm'), row('Firm Location')))
    The A. Morin firm is positioned in France.
    The A. Morin firm is positioned in France.
    The A. Morin firm is positioned in France.
    The A. Morin firm is positioned in France.
    The Acalli firm is positioned in U.S.A..
    The Acalli firm is positioned in U.S.A..
    The Adi firm is positioned in Fiji.
    The Adi firm is positioned in Fiji.
    The Adi firm is positioned in Fiji.
    The Adi firm is positioned in Fiji.
    The Aequare (Gianduja) firm is positioned in Ecuador.
    The Aequare (Gianduja) firm is positioned in Ecuador.
    The Ah Cacao firm is positioned in Mexico.
    The Akesson's (Pralus) firm is positioned in Switzerland.
    The Akesson's (Pralus) firm is positioned in Switzerland.
    The Akesson's (Pralus) firm is positioned in Switzerland.
    The Alain Ducasse firm is positioned in France.
    The Alain Ducasse firm is positioned in France.
    The Alain Ducasse firm is positioned in France.
    The Alain Ducasse firm is positioned in France.
    The Alain Ducasse firm is positioned in France.
    The Alexandre firm is positioned in Netherlands.
    The Alexandre firm is positioned in Netherlands.
    The Alexandre firm is positioned in Netherlands.
    The Alexandre firm is positioned in Netherlands.
    The Altus aka Cao Artisan firm is positioned in U.S.A..
    The Altus aka Cao Artisan firm is positioned in U.S.A..
    The Altus aka Cao Artisan firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amano firm is positioned in U.S.A..
    The Amatller (Simon Coll) firm is positioned in Spain.
    The Amatller (Simon Coll) firm is positioned in Spain.
    The Amatller (Simon Coll) firm is positioned in Spain.
    The Amatller (Simon Coll) firm is positioned in Spain.
    The Amazona firm is positioned in Peru.
    The Ambrosia firm is positioned in Canada.
    The Ambrosia firm is positioned in Canada.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The Amedei firm is positioned in Italy.
    The AMMA firm is positioned in Brazil.
    The AMMA firm is positioned in Brazil.
    The AMMA firm is positioned in Brazil.
    The AMMA firm is positioned in Brazil.
    The AMMA firm is positioned in Brazil.
    The Anahata firm is positioned in U.S.A..
    The Animas firm is positioned in U.S.A..
    The Ara firm is positioned in France.
    The Ara firm is positioned in France.
    The Arete firm is positioned in U.S.A..
    The Artisan du Chocolat firm is positioned in U.Okay..
    The Artisan du Chocolat (Casa Luker) firm is positioned in U.Okay..
    The Askinosie firm is positioned in U.S.A..
    The Askinosie firm is positioned in U.S.A..
    The Askinosie firm is positioned in U.S.A..
    The Askinosie firm is positioned in U.S.A..
    The Askinosie firm is positioned in U.S.A..
    The Askinosie firm is positioned in U.S.A..
    The Bahen & Co. firm is positioned in Australia.
    The Bakau firm is positioned in Peru.
    The Bakau firm is positioned in Peru.
    The Bar Au Chocolat firm is positioned in U.S.A..
    The Bar Au Chocolat firm is positioned in U.S.A..
    The Bar Au Chocolat firm is positioned in U.S.A..
    The Bar Au Chocolat firm is positioned in U.S.A..
    The Bar Au Chocolat firm is positioned in U.S.A..
    The Baravelli's firm is positioned in Wales.
    The Batch firm is positioned in U.S.A..
    The Batch firm is positioned in U.S.A..
    The Batch firm is positioned in U.S.A..
    The Beau Cacao firm is positioned in U.Okay..
    The Beau Cacao firm is positioned in U.Okay..
    The Beehive firm is positioned in U.S.A..
    The Beehive firm is positioned in U.S.A..
    The Beehive firm is positioned in U.S.A..
    The Beehive firm is positioned in U.S.A..
    The Belcolade firm is positioned in Belgium.
    The Belcolade firm is positioned in Belgium.
    The Belcolade firm is positioned in Belgium.
    The Belcolade firm is positioned in Belgium.
    The Bellflower firm is positioned in U.S.A..
    The Bellflower firm is positioned in U.S.A..
    The Classic Plantations (Tulicorp) firm is positioned in U.S.A..
    The Violet Sky firm is positioned in U.S.A..
    The Wm firm is positioned in U.S.A..
    The Wm firm is positioned in U.S.A..
    The Woodblock firm is positioned in U.S.A..
    The Xocolat firm is positioned in Domincan Republic.
    The Xocolla firm is positioned in U.S.A..
    The Xocolla firm is positioned in U.S.A..
    The Zart Pralinen firm is positioned in Austria.
    The Zart Pralinen firm is positioned in Austria.
    The Zokoko firm is positioned in Australia.

Lesen von JSON -Dateien

Ein weiteres beliebtes Dateiformat, das wir hauptsächlich zum Speichern und Austausch von Daten verwenden, ist JSON. JSON steht für JavaScript-Objektnotation und ermöglicht es uns, Daten mit Schlüsselwertpaaren zu speichern, die durch Kommas getrennt sind.

In diesem Abschnitt werden wir eine JSON -Datei laden und damit als JSON -Objekt arbeiten – nicht als Textdatei. Dazu müssen wir das JSON -Modul importieren. Dann in der with Kontextmanager verwenden wir die load() Methode, die zur json Objekt. Es lädt den Inhalt der Datei und speichert sie in der context Variable als Wörterbuch. Versuchen wir es, aber bevor Sie den Code ausführen, laden Sie die herunter film.json Datei und in das aktuelle Arbeitsverzeichnis einlegen.

import json
with open('film.json') as f:
    content material = json.load(f)
    print(content material)
    {'Title': 'Bicentennial Man', 'Launch Date': 'Dec 17 1999', 'MPAA Ranking': 'PG', 'Working Time min': 132, 'Distributor': 'Walt Disney Photos', 'Supply': 'Primarily based on Guide/Brief Story', 'Main Style': 'Drama', 'Inventive Sort': 'Science Fiction', 'Director': 'Chris Columbus', 'Rotten Tomatoes Ranking': 38, 'IMDB Ranking': 6.4, 'IMDB Votes': 28827}

Überprüfen wir den Datentyp der content material Variable:

print(sort(content material))
    <class 'dict'>

Sein Datentyp ist ein Wörterbuch. So können wir auf jede in der JSON -Datei gespeicherte Informationen mit ihrem Schlüssel zugreifen. Mal sehen, wie wir Daten daraus abrufen können:

print('{} directed by {}'.format(content material('Title'), content material('Director')))
    Bicentennial Man directed by Chris Columbus

Einpacken

In diesem Tutorial wurde die Dateibehandlung in Python erläutert und sich auf das Lesen des Inhalts von Dateien konzentriert. Sie haben etwas über das gelernt open() Integrierte Funktion, die mit dem Kontextmanager und zum Lesen der gemeinsamen Dateitypen wie Textual content, CSV und JSON.

Von admin

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert