I / O súborov Pythonu: Čítanie a zápis súborov v Pythone

V tomto výučbe sa dozviete o operáciách so súbormi v Pythone. Presnejšie povedané, otvorenie súboru, jeho načítanie, zápis do neho, zatvorenie a rôzne metódy súborov, ktoré by ste mali poznať.

Video: Čítanie a zápis súborov v Pythone

Súbory

Súbory sú pomenované ako umiestnenia na disku na ukladanie súvisiacich informácií. Používajú sa na trvalé ukladanie údajov v energeticky nezávislej pamäti (napr. Na pevnom disku).

Pretože pamäť RAM (Random Access Memory) je nestála (ktorá stráca údaje, keď je počítač vypnutý), používame súbory na budúce použitie údajov ich trvalým ukladaním.

Ak chceme zo súboru čítať alebo do neho zapisovať, musíme ho najskôr otvoriť. Keď skončíme, musí sa to uzavrieť, aby sa uvoľnili zdroje spojené so súborom.

Preto v Pythone operácia so súbormi prebieha v nasledujúcom poradí:

  1. Otvorte súbor
  2. Čítanie alebo zápis (vykonanie operácie)
  3. Zatvorte súbor

Otváranie súborov v Pythone

Python má zabudovanú open()funkciu na otvorenie súboru. Táto funkcia vracia objekt súboru, ktorý sa tiež nazýva handle, pretože sa používa na zodpovedajúce načítanie alebo úpravu súboru.

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

Pri otváraní súboru môžeme určiť režim. V režime určíme, či chceme súbor čítať r, písať walebo pripojiť a. Môžeme tiež určiť, či chceme súbor otvoriť v textovom alebo binárnom režime.

Predvolená hodnota je čítanie v textovom režime. V tomto režime dostaneme pri načítaní zo súboru reťazce.

Na druhej strane binárny režim vracia bajty a toto je režim, ktorý sa použije pri práci s netextovými súbormi, ako sú obrázky alebo spustiteľné súbory.

Režim Popis
r Otvorí súbor na čítanie. (predvolené)
w Otvorí súbor na písanie. Vytvorí nový súbor, ak neexistuje, alebo ho skráti, ak existuje.
x Otvorí súbor na exkluzívne vytvorenie. Ak súbor už existuje, operácia zlyhá.
a Otvorí súbor na pripojenie na konci súboru bez jeho skrátenia. Vytvorí nový súbor, ak neexistuje.
t Otvára sa v textovom režime. (predvolené)
b Otvára sa v binárnom režime.
+ Otvára súbor na aktualizáciu (čítanie a zápis)
 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

Na rozdiel od iných jazykov znak aneznamená číslo 97, kým nebude zakódovaný pomocou ASCII(alebo iného ekvivalentného kódovania).

Predvolené kódovanie je navyše závislé od platformy. V systéme Windows je to cp1252ale utf-8v systéme Linux.

Nesmieme sa teda spoliehať ani na predvolené kódovanie, inak sa bude náš kód na rôznych platformách správať odlišne.

Pri práci so súbormi v textovom režime sa preto dôrazne odporúča určiť typ kódovania.

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

Zatváranie súborov v Pythone

Keď skončíme s vykonávaním operácií na súbore, musíme súbor správne zavrieť.

Zatvorením súboru sa uvoľnia zdroje, ktoré boli so súborom spojené. Robí sa to pomocou close()metódy dostupnej v Pythone.

Python má zberača odpadkov na čistenie nereferenčných objektov, ale nesmieme sa spoliehať na to, že zavrie súbor.

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

Táto metóda nie je úplne bezpečná. Ak dôjde k výnimke, keď vykonávame so súborom nejakú operáciu, kód sa ukončí bez zatvorenia súboru.

Bezpečnejším spôsobom je použiť pokus … konečne blok.

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

Týmto spôsobom zaručujeme, že súbor je správne zatvorený, aj keď sa vyskytne výnimka, ktorá spôsobí zastavenie toku programu.

Najlepším spôsobom, ako zavrieť súbor, je použitie withpríkazu. To zaisťuje, že sa súbor zatvorí, keď sa ukončí blok vo vnútri withpríkazu.

close()Metódu nemusíme výslovne nazývať . Robí sa to interne.

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

Zápis do súborov v Pythone

Aby sme mohli zapísať do súboru v Pythone, musíme ho otvoriť v režime zápisu w, pridania aalebo exkluzívneho vytvorenia x.

S wrežimom musíme byť opatrní , pretože ak súbor už existuje, prepíše sa do súboru. Z tohto dôvodu sa všetky predchádzajúce údaje vymažú.

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) Zapíše reťazec s do súboru a vráti počet napísaných znakov.
linky (linky) Zapíše zoznam riadkov do súboru.

Zaujímavé články...