Python File I / O: Odczyt i zapis plików w Pythonie

W tym samouczku dowiesz się o operacjach na plikach w języku Python. Mówiąc dokładniej, otwieranie pliku, czytanie z niego, zapisywanie do niego, zamykanie go i różne metody plików, o których powinieneś wiedzieć.

Wideo: czytanie i pisanie plików w Pythonie

Akta

Pliki to nazwane lokalizacje na dysku, w których przechowywane są powiązane informacje. Służą do trwałego przechowywania danych w pamięci nieulotnej (np. Na dysku twardym).

Ponieważ pamięć o dostępie swobodnym (RAM) jest ulotna (która traci swoje dane po wyłączeniu komputera), używamy plików do przyszłego wykorzystania danych, przechowując je na stałe.

Kiedy chcemy czytać lub zapisywać do pliku, musimy go najpierw otworzyć. Kiedy skończymy, należy go zamknąć, aby zasoby powiązane z plikiem zostały zwolnione.

Dlatego w Pythonie operacja na plikach odbywa się w następującej kolejności:

  1. Otworzyć plik
  2. Czytaj lub pisz (wykonaj operację)
  3. Zamknij plik

Otwieranie plików w Pythonie

Python ma wbudowaną open()funkcję do otwierania pliku. Ta funkcja zwraca obiekt pliku, zwany także uchwytem, ​​ponieważ jest używany do odpowiedniego odczytu lub modyfikacji pliku.

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

Tryb możemy określić podczas otwierania pliku. W trybie określamy, czy chcemy czytać r, zapisywać wczy dołączać ado pliku. Możemy również określić, czy chcemy otworzyć plik w trybie tekstowym czy binarnym.

Domyślnie jest to czytanie w trybie tekstowym. W tym trybie podczas odczytu z pliku otrzymujemy ciągi znaków.

Z drugiej strony tryb binarny zwraca bajty i jest to tryb używany w przypadku plików nietekstowych, takich jak obrazy lub pliki wykonywalne.

Tryb Opis
r Otwiera plik do odczytu. (domyślna)
w Otwiera plik do zapisu. Tworzy nowy plik, jeśli nie istnieje, lub obcina go, jeśli istnieje.
x Otwiera plik do tworzenia na wyłączność. Jeśli plik już istnieje, operacja nie powiedzie się.
a Otwiera plik do dołączenia na końcu pliku bez obcinania go. Tworzy nowy plik, jeśli nie istnieje.
t Otwiera się w trybie tekstowym. (domyślna)
b Otwiera się w trybie binarnym.
+ Otwiera plik do aktualizacji (odczyt i zapis)
 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

W przeciwieństwie do innych języków znak anie implikuje liczby 97, dopóki nie zostanie zakodowany przy użyciu ASCII(lub innego równoważnego kodowania).

Ponadto domyślne kodowanie zależy od platformy. W systemie Windows jest, cp1252ale utf-8w Linuksie.

Dlatego nie możemy również polegać na domyślnym kodowaniu, w przeciwnym razie nasz kod będzie zachowywał się inaczej na różnych platformach.

Dlatego podczas pracy z plikami w trybie tekstowym zdecydowanie zaleca się określenie typu kodowania.

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

Zamykanie plików w Pythonie

Kiedy zakończymy wykonywanie operacji na pliku, musimy go odpowiednio zamknąć.

Zamknięcie pliku zwalnia zasoby, które były z nim powiązane. Odbywa się to za pomocą close()metody dostępnej w Pythonie.

Python ma moduł odśmiecania pamięci do czyszczenia obiektów bez odwołań, ale nie możemy na nim polegać przy zamykaniu pliku.

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

Ta metoda nie jest całkowicie bezpieczna. Jeśli wystąpi wyjątek, gdy wykonujemy jakąś operację na pliku, kod kończy działanie bez zamykania pliku.

A safer way is to use a try… finally block.

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

This way, we are guaranteeing that the file is properly closed even if an exception is raised that causes program flow to stop.

The best way to close a file is by using the with statement. This ensures that the file is closed when the block inside the with statement is exited.

We don't need to explicitly call the close() method. It is done internally.

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

Writing to Files in Python

In order to write into a file in Python, we need to open it in write w, append a or exclusive creation x mode.

We need to be careful with the w mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are erased.

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) Zapisuje ciąg s do pliku i zwraca liczbę zapisanych znaków.
writelines (linie) Zapisuje listę wierszy do pliku.

Interesujące artykuły...