Python File I / O: Fájlok olvasása és írása a Pythonban

Ebben az oktatóanyagban megismerheti a Python fájlműveleteket. Pontosabban, egy fájl megnyitása, olvasás belőle, beírás, bezárás és különféle fájlmódszerek, amelyekkel tisztában kell lennie.

Videó: Fájlok olvasása és írása Pythonban

Fájlok

A fájlok meg vannak nevezve a lemezen a kapcsolódó információk tárolására. Arra szolgálnak, hogy állandóan tárolják az adatokat egy nem felejtő memóriában (pl. Merevlemez).

Mivel a véletlen hozzáférésű memória (RAM) ingatag (ami elveszíti az adatait, amikor a számítógépet kikapcsolják), fájlokat használunk az adatok jövőbeni felhasználásához, végleges tárolásukkal.

Ha fájlból akarunk olvasni vagy írni, akkor először meg kell nyitnunk. Ha elkészültünk, le kell zárni, hogy a fájlhoz kötött erőforrások felszabaduljanak.

Ezért a Pythonban a fájlművelet a következő sorrendben történik:

  1. Nyisson meg egy fájlt
  2. Olvasás vagy írás (művelet végrehajtása)
  3. Zárja be a fájlt

Fájlok megnyitása a Pythonban

A Python beépített open()funkcióval rendelkezik egy fájl megnyitásához. Ez a függvény egy fájl objektumot ad vissza, más néven fogantyút, mivel arra használják, hogy a fájlt ennek megfelelően olvassa vagy módosítsa.

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

Megadhatjuk a módot egy fájl megnyitása közben. Módban megadjuk, hogy olvasni r, írni wvagy csatolni aakarjuk-e a fájlt. Azt is megadhatjuk, hogy szöveges vagy bináris módban szeretnénk-e megnyitni a fájlt.

Az alapértelmezés szöveges módban történő olvasás. Ebben a módban húrokat kapunk, amikor a fájlból olvasunk.

Másrészt a bináris mód visszatér bájtokat, és ezt a módot kell használni, ha nem szöveges fájlokkal, például képekkel vagy futtatható fájlokkal foglalkozunk.

Mód Leírás
r Megnyit egy fájlt olvasásra. (alapértelmezett)
w Megnyit egy fájlt írásra. Új fájlt hoz létre, ha nem létezik, vagy megcsonkítja a fájlt, ha létezik.
x Fájl megnyitása exkluzív létrehozáshoz. Ha a fájl már létezik, a művelet sikertelen.
a Megnyit egy fájlt a fájl végén csatolásra anélkül, hogy megcsonkítaná. Új fájlt hoz létre, ha nem létezik.
t Megnyílik szöveges módban. (alapértelmezett)
b Bináris módban nyílik meg.
+ Megnyit egy fájlt a frissítéshez (olvasás és írás)
 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

Más nyelvektől eltérően a karakter acsak akkor jelenti a 97-es számot, ha azt kódolják ASCII(vagy más egyenértékű kódolással).

Ezenkívül az alapértelmezett kódolás platformfüggő. Az ablakok, ez cp1252azonban utf-8a Linux.

Tehát nem szabad támaszkodnunk az alapértelmezett kódolásra, különben a kódunk másképp fog viselkedni a különböző platformokon.

Ezért, ha fájlokkal dolgozik szöveges módban, erősen ajánlott megadni a kódolási típust.

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

Fájlok bezárása a Pythonban

Ha befejeztük a fájl műveleteinek végrehajtását, akkor megfelelően le kell zárnunk a fájlt.

A fájl bezárása felszabadítja a fájlhoz kötött erőforrásokat. A close()Pythonban elérhető módszerrel történik .

A Python rendelkezik szemétgyűjtővel a nem hivatkozott objektumok megtisztítására, de nem szabad rá hagyatkoznunk a fájl bezárásakor.

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

Ez a módszer nem teljesen biztonságos. Ha kivétel történik, amikor valamilyen műveletet hajtunk végre a fájllal, a kód kilép a fájl bezárása nélkül.

Biztonságosabb módszer egy próbálkozás használata … végül blokkolja.

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

Így garantáljuk a fájl megfelelő bezárását, még akkor is, ha olyan kivétel merül fel, amely miatt a program folyamata leáll.

A fájl bezárásának legjobb módja az withutasítás használata. Ez biztosítja, hogy a fájl bezáruljon, amikor az withutasítás belsejében lévő blokk kilép.

Nem kell kifejezetten hívnunk a close()módszert. Belsőleg történik.

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

Írás fájlokba Python-ban

Ahhoz, hogy egy fájlba írhassunk a Pythonban, meg kell nyitnunk írási w, csatolási avagy kizárólagos létrehozási xmódban.

Vigyáznunk kell a wmóddal, mivel felülírja a fájlba, ha már létezik. Emiatt az összes korábbi adat törlődik.

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) Írja az s karakterláncot a fájlba, és visszaadja az írt karakterek számát.
írósorok (sorok) Írja a fájl sorainak listáját.

érdekes cikkek...