I / O file Python: lettura e scrittura di file in Python

In questo tutorial imparerai le operazioni sui file Python. Più specificamente, apertura di un file, lettura da esso, scrittura in esso, chiusura e vari metodi di file di cui dovresti essere a conoscenza.

Video: lettura e scrittura di file in Python

File

I file sono percorsi denominati su disco per memorizzare le informazioni correlate. Sono utilizzati per memorizzare in modo permanente i dati in una memoria non volatile (ad es. Disco rigido).

Poiché la memoria ad accesso casuale (RAM) è volatile (che perde i suoi dati quando il computer viene spento), utilizziamo i file per un uso futuro dei dati archiviandoli in modo permanente.

Quando vogliamo leggere o scrivere su un file, dobbiamo prima aprirlo. Quando abbiamo finito, deve essere chiuso in modo che le risorse che sono legate al file vengano liberate.

Quindi, in Python, un'operazione sui file avviene nel seguente ordine:

  1. Apri un file
  2. Leggere o scrivere (eseguire l'operazione)
  3. Chiudi il file

Apertura di file in Python

Python ha una open()funzione incorporata per aprire un file. Questa funzione restituisce un oggetto file, chiamato anche handle, poiché viene utilizzato per leggere o modificare il file di conseguenza.

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

Possiamo specificare la modalità durante l'apertura di un file. In modalità, specifichiamo se vogliamo leggere r, scrivere wo aggiungere aal file. Possiamo anche specificare se vogliamo aprire il file in modalità testo o in modalità binaria.

L'impostazione predefinita è la lettura in modalità testo. In questa modalità, otteniamo le stringhe durante la lettura dal file.

D'altra parte, la modalità binaria restituisce byte e questa è la modalità da utilizzare quando si tratta di file non di testo come immagini o file eseguibili.

Modalità Descrizione
r Apre un file per la lettura. (predefinito)
w Apre un file per la scrittura. Crea un nuovo file se non esiste o tronca il file se esiste.
x Apre un file per la creazione esclusiva. Se il file esiste già, l'operazione non riesce.
a Apre un file da aggiungere alla fine del file senza troncarlo. Crea un nuovo file se non esiste.
t Si apre in modalità testo. (predefinito)
b Si apre in modalità binaria.
+ Apre un file per l'aggiornamento (lettura e scrittura)
 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

A differenza di altre lingue, il carattere anon implica il numero 97 fino a quando non viene codificato utilizzando ASCII(o altre codifiche equivalenti).

Inoltre, la codifica predefinita dipende dalla piattaforma. In Windows, è cp1252solo utf-8in Linux.

Quindi, non dobbiamo fare affidamento anche sulla codifica predefinita, altrimenti il ​​nostro codice si comporterà in modo diverso nelle diverse piattaforme.

Pertanto, quando si lavora con i file in modalità testo, si consiglia vivamente di specificare il tipo di codifica.

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

Chiusura dei file in Python

Quando abbiamo finito di eseguire le operazioni sul file, dobbiamo chiudere correttamente il file.

La chiusura di un file libererà le risorse che erano legate al file. Viene eseguito utilizzando il close()metodo disponibile in Python.

Python ha un garbage collector per ripulire oggetti non referenziati ma non dobbiamo fare affidamento su di esso per chiudere il file.

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

Questo metodo non è del tutto sicuro. Se si verifica un'eccezione durante l'esecuzione di alcune operazioni con il file, il codice esce senza chiudere il file.

Un modo più sicuro è usare un tentativo … finalmente bloccare.

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

In questo modo, garantiamo che il file venga chiuso correttamente anche se viene sollevata un'eccezione che causa l'arresto del flusso del programma.

Il modo migliore per chiudere un file è utilizzare l' withistruzione. Ciò garantisce che il file venga chiuso quando withsi esce dal blocco all'interno dell'istruzione.

Non è necessario chiamare esplicitamente il close()metodo. È fatto internamente.

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

Scrittura su file in Python

Per scrivere in un file in Python, dobbiamo aprirlo in modalità di scrittura w, aggiunta ao creazione esclusiva x.

Dobbiamo stare attenti con la wmodalità, poiché sovrascriverà nel file se esiste già. A causa di ciò, tutti i dati precedenti vengono cancellati.

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) Scrive la stringa s nel file e restituisce il numero di caratteri scritti.
writelines (linee) Scrive un elenco di righe nel file.

Articoli interessanti...