Python File I / O: Lukea ja kirjoittaa tiedostoja Pythonissa

Tässä opetusohjelmassa opit Python-tiedostotoiminnoista. Tarkemmin sanottuna tiedoston avaaminen, lukeminen siitä, kirjoittaminen siihen, sulkeminen ja erilaiset tiedostomenetelmät, joista sinun tulisi olla tietoinen.

Video: Tiedostojen lukeminen ja kirjoittaminen Pythonissa

Tiedostot

Tiedostot on nimetty levykkeiksi niihin liittyvien tietojen tallentamiseksi. Niitä käytetään tietojen pysyvään tallentamiseen haihtumattomaan muistiin (esim. Kiintolevylle).

Koska Random Access Memory (RAM) on epävakaa (joka menettää tietonsa, kun tietokone sammutetaan), käytämme tiedostoja tietojen myöhempää käyttöä varten tallentamalla ne pysyvästi.

Kun haluamme lukea tiedostosta tai kirjoittaa siihen, meidän on ensin avattava se. Kun olemme valmis, se on suljettava, jotta tiedostoon sidotut resurssit vapautuvat.

Näin ollen Pythonissa tiedostotoiminta tapahtuu seuraavassa järjestyksessä:

  1. Avaa tiedosto
  2. Lue tai kirjoita (suorita toiminto)
  3. Sulje tiedosto

Tiedostojen avaaminen Pythonissa

Pythonissa on sisäänrakennettu open()toiminto tiedoston avaamiseksi. Tämä toiminto palauttaa tiedostoobjektin, jota kutsutaan myös kahvaksi, koska sitä käytetään tiedoston lukemiseen tai muokkaamiseen vastaavasti.

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

Voimme määrittää tilan tiedoston avaamisen yhteydessä. Tilassa määritämme, haluatko lukea r, kirjoittaa wtai liittää atiedostoon. Voimme myös määrittää, haluatko avata tiedoston tekstitilassa tai binaaritilassa.

Oletusarvo on lukeminen tekstitilassa. Tässä tilassa saamme merkkijonoja, kun luemme tiedostosta.

Toisaalta binaaritila palauttaa tavuja, ja tätä tilaa käytetään käsiteltäessä muita kuin tekstitiedostoja, kuten kuvia tai suoritettavia tiedostoja.

Tila Kuvaus
r Avaa tiedoston lukemista varten. (oletus)
w Avaa tiedoston kirjoittamista varten. Luo uuden tiedoston, jos sitä ei ole, tai katkaisee tiedoston, jos sitä on.
x Avaa tiedoston yksinomaista luomista varten. Jos tiedosto on jo olemassa, toiminto epäonnistuu.
a Avaa tiedoston liitettäväksi tiedoston loppuun katkaisematta sitä. Luo uuden tiedoston, jos sitä ei ole olemassa.
t Avautuu tekstitilassa. (oletus)
b Avautuu binaaritilassa.
+ Avaa tiedoston päivitettäväksi (lukeminen ja kirjoittaminen)
 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

Toisin kuin muilla kielillä, merkki aei tarkoita numeroa 97, ennen kuin se on koodattu käyttämällä ASCII(tai muita vastaavia koodauksia).

Lisäksi oletuskoodaus riippuu alustasta. Ikkunoissa on cp1252mutta utf-8Linux.

Joten emme saa luottaa myös oletuskoodaukseen, muuten koodimme käyttäytyy eri tavoin eri alustoilla.

Siksi, kun työskentelet tiedostojen kanssa tekstitilassa, on erittäin suositeltavaa määrittää koodaustyyppi.

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

Tiedostojen sulkeminen Pythonissa

Kun tiedosto on suoritettu loppuun, tiedosto on suljettava oikein.

Tiedoston sulkeminen vapauttaa tiedostoon sidotut resurssit. Se tehdään käyttämällä close()Pythonissa käytettävissä olevaa menetelmää.

Pythonilla on roskien keräilijä viemättömien objektien puhdistamiseen, mutta emme saa luottaa siihen sulkemaan tiedosto.

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

Tämä menetelmä ei ole täysin turvallinen. Jos poikkeus tapahtuu, kun suoritamme jonkin toiminnon tiedostolla, koodi poistuu sulkematta tiedostoa.

Turvallisempi tapa on käyttää yritystä … lopulta estää.

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

Tällä tavoin takaamme, että tiedosto on suljettu oikein, vaikka esiin tuotaisiin poikkeus, joka aiheuttaa ohjelmavirran pysähtymisen.

Paras tapa sulkea tiedosto on käyttää withlausetta. Tämä varmistaa, että tiedosto suljetaan, kun lauseen lohko withpoistuu.

Meidän ei tarvitse nimenomaisesti kutsua close()menetelmää. Se tehdään sisäisesti.

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

Kirjoittaminen tiedostoihin Pythonissa

Jotta voimme kirjoittaa tiedostoon Pythonissa, meidän on avattava se kirjoitus- w, liite- atai yksinoikeudellisessa luomistilassa x.

Meidän on oltava varovaisia wtilassa, koska se korvaa tiedoston, jos se on jo olemassa. Tämän vuoksi kaikki edelliset tiedot poistetaan.

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) Kirjoittaa merkkijonon s tiedostoon ja palauttaa kirjoitettujen merkkien määrän.
kirjoituslinjat (rivit) Kirjoittaa tiedostoon luettelon riveistä.

Mielenkiintoisia artikkeleita...