I / O souborů Pythonu: Čtení a zápis souborů v Pythonu

V tomto kurzu se dozvíte o operacích se soubory Pythonu. Přesněji řečeno, otevření souboru, čtení z něj, zápis do něj, uzavření a různé metody souborů, které byste měli znát.

Video: Čtení a zápis souborů v Pythonu

Soubory

Soubory jsou pojmenovány jako umístění na disku pro uložení souvisejících informací. Používají se k trvalému ukládání dat do energeticky nezávislé paměti (např. Pevného disku).

Vzhledem k tomu, že paměť RAM (Random Access Memory) je nestálá (která při vypnutí počítače ztrácí svá data), používáme soubory pro budoucí použití dat jejich trvalým ukládáním.

Když chceme ze souboru číst nebo do něj zapisovat, musíme jej nejprve otevřít. Až budeme hotovi, je třeba jej uzavřít, aby se uvolnily prostředky svázané se souborem.

Proto v Pythonu probíhá operace se soubory v následujícím pořadí:

  1. Otevřít soubor
  2. Čtení nebo zápis (provedení operace)
  3. Zavřete soubor

Otevírání souborů v Pythonu

Python má vestavěnou open()funkci pro otevření souboru. Tato funkce vrací objekt souboru, který se také nazývá popisovač, protože se používá k odpovídajícímu čtení nebo úpravám souboru.

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

Můžeme určit režim při otevírání souboru. V režimu určíme, zda chceme soubor číst r, zapisovat wnebo připojit a. Můžeme také určit, zda chceme soubor otevřít v textovém nebo binárním režimu.

Výchozí hodnota je čtení v textovém režimu. V tomto režimu získáváme řetězce při čtení ze souboru.

Na druhou stranu binární režim vrací bajty a toto je režim, který se má použít při práci s netextovými soubory, jako jsou obrázky nebo spustitelné soubory.

Režim Popis
r Otevře soubor ke čtení. (výchozí)
w Otevře soubor pro zápis. Vytvoří nový soubor, pokud neexistuje, nebo zkrátí soubor, pokud existuje.
x Otevře soubor pro exkluzivní tvorbu. Pokud soubor již existuje, operace se nezdaří.
a Otevře soubor pro připojení na konec souboru, aniž byste jej ořezali. Vytvoří nový soubor, pokud neexistuje.
t Otevírá se v textovém režimu. (výchozí)
b Otevírá se v binárním režimu.
+ Otevře soubor pro aktualizaci (čtení 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 rozdíl od jiných jazyků znak aneimplikuje číslo 97, dokud není zakódován pomocí ASCII(nebo jiného ekvivalentního kódování).

Výchozí kódování je navíc závislé na platformě. V systému Windows je to cp1252ale utf-8v systému Linux.

Nesmíme se tedy spoléhat ani na výchozí kódování, jinak se náš kód bude na různých platformách chovat odlišně.

Při práci se soubory v textovém režimu se proto důrazně doporučuje určit typ kódování.

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

Zavírání souborů v Pythonu

Po dokončení operací se souborem musíme soubor správně zavřít.

Uzavřením souboru uvolníte prostředky, které byly se souborem svázány. Dělá se to pomocí close()metody dostupné v Pythonu.

Python má sběrač odpadků, který čistí objekty bez odkazu, ale nesmíme se spoléhat na to, že soubor zavře.

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

Tato metoda není zcela bezpečná. Pokud dojde k výjimce, když provádíme nějakou operaci se souborem, kód se ukončí bez zavření souboru.

Bezpečnějším způsobem je použít pokus … konečně blok.

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

Tímto způsobem zaručujeme, že soubor je správně uzavřen, i když je vyvolána výjimka, která způsobí zastavení toku programu.

Nejlepší způsob, jak zavřít soubor, je použití withpříkazu. Tím je zajištěno, že soubor je uzavřen, když withje ukončen blok uvnitř příkazu.

close()Metodu nemusíme explicitně volat . Dělá se to interně.

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

Zápis do souborů v Pythonu

Abychom mohli v Pythonu zapisovat do souboru, musíme jej otevřít v režimu zápisu w, přidání anebo exkluzivního vytvoření x.

S wrežimem musíme být opatrní , protože se přepíše do souboru, pokud již existuje. Z tohoto důvodu jsou vymazána všechna předchozí data.

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 řetězec s do souboru a vrátí počet zapsaných znaků.
linky (linky) Zapíše seznam řádků do souboru.

Zajímavé články...