Python File I / O: bestanden lezen en schrijven in Python

In deze tutorial leer je over Python-bestandsbewerkingen. Meer specifiek, het openen van een bestand, ervan lezen, erin schrijven, het sluiten en verschillende bestandsmethoden waarvan u op de hoogte moet zijn.

Video: bestanden lezen en schrijven in Python

Bestanden

Bestanden hebben een naam op de schijf om gerelateerde informatie op te slaan. Ze worden gebruikt om gegevens permanent op te slaan in een niet-vluchtig geheugen (bijv. Harde schijf).

Omdat Random Access Memory (RAM) vluchtig is (dat zijn gegevens verliest wanneer de computer wordt uitgeschakeld), gebruiken we bestanden voor toekomstig gebruik van de gegevens door ze permanent op te slaan.

Als we willen lezen van of schrijven naar een bestand, moeten we het eerst openen. Als we klaar zijn, moet het worden gesloten, zodat de bronnen die aan het bestand zijn gekoppeld, worden vrijgemaakt.

Daarom vindt in Python een bestandsbewerking plaats in de volgende volgorde:

  1. Een bestand openen
  2. Lezen of schrijven (bewerking uitvoeren)
  3. Sluit het bestand

Bestanden openen in Python

Python heeft een ingebouwde open()functie om een ​​bestand te openen. Deze functie retourneert een bestandsobject, ook wel een handle genoemd, omdat het wordt gebruikt om het bestand dienovereenkomstig te lezen of aan te passen.

 >>> f = open("test.txt") # open file in current directory >>> f = open("C:/Python38/README.txt") # specifying full path

We kunnen de modus specificeren tijdens het openen van een bestand. In de modus specificeren we of we het bestand willen lezen r, schrijven wof toevoegen a. We kunnen ook specificeren of we het bestand in tekstmodus of binaire modus willen openen.

De standaardinstelling is lezen in tekstmodus. In deze modus krijgen we strings bij het lezen van het bestand.

Aan de andere kant retourneert de binaire modus bytes en dit is de modus die moet worden gebruikt bij niet-tekstbestanden zoals afbeeldingen of uitvoerbare bestanden.

Modus Omschrijving
r Opent een bestand om te lezen. (standaard)
w Opent een bestand om te schrijven. Maakt een nieuw bestand aan als het nog niet bestaat of kapt het bestand af als het bestaat.
x Opent een bestand voor exclusieve creatie. Als het bestand al bestaat, mislukt de bewerking.
a Opent een bestand om aan het einde van het bestand toe te voegen zonder het af te kappen. Maakt een nieuw bestand aan als het nog niet bestaat.
t Opent in tekstmodus. (standaard)
b Opent in binaire modus.
+ Opent een bestand om te updaten (lezen en schrijven)
 f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp.webp",'r+b') # read and write in binary mode

In tegenstelling tot andere talen, aimpliceert het teken pas het getal 97 als het is gecodeerd met ASCII(of andere gelijkwaardige coderingen).

Bovendien is de standaardcodering platformafhankelijk. In Windows is het cp1252maar utf-8in Linux.

We moeten dus niet ook vertrouwen op de standaardcodering, anders gedraagt ​​onze code zich anders op verschillende platforms.

Daarom wordt het ten zeerste aanbevolen om het coderingstype op te geven wanneer u met bestanden in tekstmodus werkt.

 f = open("test.txt", mode='r', encoding='utf-8')

Bestanden sluiten in Python

Als we klaar zijn met het uitvoeren van bewerkingen op het bestand, moeten we het bestand correct sluiten.

Als u een bestand sluit, worden de bronnen vrijgemaakt die aan het bestand waren gekoppeld. Het wordt gedaan met behulp van de close()methode die beschikbaar is in Python.

Python heeft een garbage collector om objecten zonder verwijzing op te ruimen, maar we moeten er niet op vertrouwen om het bestand te sluiten.

 f = open("test.txt", encoding = 'utf-8') # perform file operations f.close()

Deze methode is niet helemaal veilig. Als er een uitzondering optreedt wanneer we een bewerking met het bestand uitvoeren, wordt de code afgesloten zonder het bestand te sluiten.

Een veiligere manier is om een ​​try … eindelijk te blokkeren.

 try: f = open("test.txt", encoding = 'utf-8') # perform file operations finally: f.close()

Op deze manier garanderen we dat het bestand correct wordt gesloten, zelfs als er een uitzondering wordt gemaakt waardoor de programmastroom stopt.

De beste manier om een ​​bestand te sluiten, is door de withinstructie. Dit zorgt ervoor dat het bestand wordt gesloten wanneer het blok in de withinstructie wordt verlaten.

We hoeven de close()methode niet expliciet aan te roepen . Het wordt intern gedaan.

 with open("test.txt", encoding = 'utf-8') as f: # perform file operations

Schrijven naar bestanden in Python

Om in Python naar een bestand te schrijven, moeten we het openen in de modus schrijven w, toevoegen aof exclusief maken x.

We moeten voorzichtig zijn met de wmodus, omdat deze zal overschrijven naar het bestand als het al bestaat. Hierdoor worden alle eerdere gegevens gewist.

Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.

 with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file") f.write("This file") f.write("contains three lines")

This program will create a new file named test.txt in the current directory if it does not exist. If it does exist, it is overwritten.

We must include the newline characters ourselves to distinguish the different lines.

Reading Files in Python

To read a file in Python, we must open the file in reading r mode.

There are various methods available for this purpose. We can use the read(size) method to read in the size number of data. If the size parameter is not specified, it reads and returns up to the end of the file.

We can read the text.txt file we wrote in the above section in the following way:

 >>> f = open("test.txt",'r',encoding = 'utf-8') >>> f.read(4) # read the first 4 data 'This' >>> f.read(4) # read the next 4 data ' is ' >>> f.read() # read in the rest till end of file 'my first fileThis filecontains three lines' >>> f.read() # further reading returns empty sting ''

We can see that the read() method returns a newline as ''. Once the end of the file is reached, we get an empty string on further reading.

We can change our current file cursor (position) using the seek() method. Similarly, the tell() method returns our current position (in number of bytes).

 >>> f.tell() # get the current file position 56 >>> f.seek(0) # bring file cursor to initial position 0 >>> print(f.read()) # read the entire file This is my first file This file contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.

 >>> for line in f:… print(line, end = '')… This is my first file This file contains three lines

In this program, the lines in the file itself include a newline character . So, we use the end parameter of the print() function to avoid two newlines when printing.

Alternatively, we can use the readline() method to read individual lines of a file. This method reads a file till the newline, including the newline character.

 >>> f.readline() 'This is my first file' >>> f.readline() 'This file' >>> f.readline() 'contains three lines' >>> f.readline() ''

Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading methods return empty values when the end of file (EOF) is reached.

 >>> f.readlines() ('This is my first file', 'This file', 'contains three lines')

Python File Methods

There are various methods available with the file object. Some of them have been used in the above examples.

Here is the complete list of methods in text mode with a brief description:

Method Description
close() Closes an opened file. It has no effect if the file is already closed.
detach() Separates the underlying binary buffer from the TextIOBase and returns it.
fileno() Returns an integer number (file descriptor) of the file.
flush() Flushes the write buffer of the file stream.
isatty() Returns True if the file stream is interactive.
read(n) Reads at most n characters from the file. Reads till end of file if it is negative or None.
readable() Returns True if the file stream can be read from.
readline(n=-1) Reads and returns one line from the file. Reads in at most n bytes if specified.
readlines(n=-1) Reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Changes the file position to offset bytes, in reference to from (start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
truncate(size=None) Resizes the file stream to size bytes. If size is not specified, resizes to current location.
writable() Returns True if the file stream can be written to.
write(s) Schrijft de tekenreeks s naar het bestand en retourneert het aantal geschreven tekens.
schrijflijnen (lijnen) Schrijft een lijst met regels naar het bestand.

Interessante artikelen...