Python File I / O: Citiți și scrieți fișiere în Python

În acest tutorial, veți afla despre operațiile de fișiere Python. Mai precis, deschiderea unui fișier, citirea acestuia, scrierea în el, închiderea acestuia și diverse metode de fișiere de care ar trebui să fiți conștienți.

Video: citirea și scrierea fișierelor în Python

Dosare

Fișierele sunt denumite locații pe disc pentru a stoca informații conexe. Acestea sunt folosite pentru stocarea permanentă a datelor într-o memorie nevolatilă (de exemplu, hard disk).

Deoarece memoria cu acces aleatoriu (RAM) este volatilă (care își pierde datele când computerul este oprit), folosim fișiere pentru utilizarea viitoare a datelor, stocându-le permanent.

Când vrem să citim sau să scriem într-un fișier, trebuie mai întâi să îl deschidem. Când am terminat, trebuie să fie închis, astfel încât resursele legate de fișier să fie eliberate.

Prin urmare, în Python, o operație de fișier are loc în următoarea ordine:

  1. Deschideți un fișier
  2. Citiți sau scrieți (efectuați operația)
  3. Închideți fișierul

Deschiderea fișierelor în Python

Python are o funcție încorporată open()pentru a deschide un fișier. Această funcție returnează un obiect fișier, numit și handle, deoarece este utilizat pentru a citi sau modifica fișierul în consecință.

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

Putem specifica modul în timp ce deschidem un fișier. În modul specificăm dacă dorim să citim r, să scriem wsau asă adăugăm la fișier. De asemenea, putem specifica dacă dorim să deschidem fișierul în modul text sau în modul binar.

Implicit este citirea în modul text. În acest mod, primim șiruri atunci când citim din fișier.

Pe de altă parte, modul binar returnează octeți și acesta este modul care trebuie utilizat atunci când se tratează fișiere non-text cum ar fi imagini sau fișiere executabile.

Mod Descriere
r Deschide un fișier pentru citire. (Mod implicit)
w Deschide un fișier pentru scriere. Creează un fișier nou dacă nu există sau trunchiază fișierul dacă există.
x Deschide un fișier pentru crearea exclusivă. Dacă fișierul există deja, operațiunea eșuează.
a Deschide un fișier pentru anexare la sfârșitul fișierului fără a-l trunchia. Creează un fișier nou dacă nu există.
t Se deschide în modul text. (Mod implicit)
b Se deschide în modul binar.
+ Deschide un fișier pentru actualizare (citire și scriere)
 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

Spre deosebire de alte limbi, caracterul anu implică numărul 97 până când nu este codificat folosind ASCII(sau alte codificări echivalente).

Mai mult, codificarea implicită depinde de platformă. În Windows, este cp1252doar utf-8în Linux.

Deci, nu trebuie să ne bazăm și pe codificarea implicită, altfel codul nostru se va comporta diferit în diferite platforme.

Prin urmare, atunci când lucrați cu fișiere în modul text, este foarte recomandat să specificați tipul de codificare.

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

Închiderea fișierelor în Python

Când am terminat cu efectuarea operațiunilor pe fișier, trebuie să închidem corect fișierul.

Închiderea unui fișier va elibera resursele care au fost legate cu fișierul. Se face folosind close()metoda disponibilă în Python.

Python are un colector de gunoi pentru a curăța obiectele neriferențiate, dar nu trebuie să ne bazăm pe acesta pentru a închide fișierul.

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

Această metodă nu este complet sigură. Dacă apare o excepție când efectuăm o operație cu fișierul, codul iese fără a închide fișierul.

O modalitate mai sigură este de a folosi un try … în cele din urmă bloc.

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

În acest fel, garantăm că fișierul este închis corect, chiar dacă este ridicată o excepție care determină oprirea fluxului de programe.

Cel mai bun mod de a închide un fișier este prin utilizarea withinstrucțiunii. Acest lucru asigură faptul că fișierul este închis când blocul din withinstrucțiune este ieșit.

Nu este nevoie să apelăm în mod explicit close()metoda. Se face intern.

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

Scrierea în fișiere în Python

Pentru a scrie într-un fișier în Python, trebuie să îl deschidem în modul de scriere w, atașare asau creație exclusivă x.

Trebuie să fim atenți la wmodul, deoarece acesta va fi suprascris în fișier dacă acesta există deja. Datorită acestui fapt, toate datele anterioare sunt șterse.

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) Scrie șirul s în fișier și returnează numărul de caractere scrise.
scrisori (linii) Scrie o listă de linii în fișier.

Articole interesante...