I / O datoteke Python: branje in pisanje datotek v Pythonu

V tej vadnici boste izvedeli več o operacijah datotek Python. Natančneje, odpiranje datoteke, branje iz nje, pisanje vanjo, zapiranje in različne metode datotek, ki se jih morate zavedati.

Video: Branje in pisanje datotek v Pythonu

Datoteke

Datoteke so imenovane lokacije na disku za shranjevanje sorodnih informacij. Uporabljajo se za trajno shranjevanje podatkov v nehlapnem pomnilniku (npr. Trdi disk).

Ker je pomnilnik z naključnim dostopom (RAM) hlapen (ki izgubi podatke, ko je računalnik izklopljen), uporabljamo datoteke za nadaljnjo uporabo podatkov, tako da jih trajno shranimo.

Ko želimo datoteko brati ali zapisovati, jo moramo najprej odpreti. Ko končamo, ga je treba zapreti, da se sprostijo viri, ki so povezani z datoteko.

V datoteki Python torej datoteka deluje v naslednjem vrstnem redu:

  1. Odprite datoteko
  2. Branje ali pisanje (izvedba operacije)
  3. Zaprite datoteko

Odpiranje datotek v Pythonu

Python ima vgrajeno open()funkcijo za odpiranje datoteke. Ta funkcija vrne datotečni objekt, imenovan tudi ročaj, saj se uporablja za ustrezno branje ali spreminjanje datoteke.

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

Način lahko določimo med odpiranjem datoteke. V načinu določimo, ali želimo datoteko prebrati r, zapisati wali dodati a. Določimo lahko tudi, ali želimo datoteko odpreti v besedilnem ali binarnem načinu.

Privzeto je branje v besedilnem načinu. V tem načinu dobimo nize, ko beremo iz datoteke.

Po drugi strani binarni način vrne bajte in to je način, ki se uporablja pri obravnavi nebesedilnih datotek, kot so slike ali izvršljive datoteke.

Način Opis
r Odpre datoteko za branje. (privzeto)
w Odpre datoteko za pisanje. Ustvari novo datoteko, če ne obstaja, ali jo okrni, če obstaja.
x Odpre datoteko za ekskluzivno ustvarjanje. Če datoteka že obstaja, operacija ne uspe.
a Odpre datoteko za dodajanje na koncu datoteke, ne da bi jo skrajšal. Ustvari novo datoteko, če ta ne obstaja.
t Odpre se v besedilnem načinu. (privzeto)
b Odpre se v binarnem načinu.
+ Odpre datoteko za posodobitev (branje in pisanje)
 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

Za razliko od drugih jezikov znak ane pomeni števila 97, dokler ni kodiran z uporabo ASCII(ali drugimi enakovrednimi kodiranji).

Poleg tega je privzeto kodiranje odvisno od platforme. V oknih je, cp1252toda utf-8v Linuxu.

Torej se ne smemo zanašati tudi na privzeto kodiranje, sicer se bo naša koda v različnih platformah obnašala drugače.

Zato je pri delu z datotekami v besedilnem načinu zelo priporočljivo določiti vrsto kodiranja.

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

Zapiranje datotek v Pythonu

Ko končamo z izvajanjem operacij v datoteki, moramo datoteko pravilno zapreti.

Zapiranje datoteke bo sprostilo vire, ki so bili povezani z datoteko. To se naredi z close()metodo, ki je na voljo v Pythonu.

Python ima zbiralnik smeti za čiščenje nepredelanih predmetov, vendar se ne smemo zanašati na to, da zapremo datoteko.

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

Ta metoda ni povsem varna. Če pride do izjeme, ko izvajamo neko operacijo z datoteko, koda zapre datoteko, ne da bi jo zaprli.

Varnejši način je uporaba poskusa … končno blokade.

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

Na ta način zagotavljamo, da je datoteka pravilno zaprta, tudi če se pojavi izjema, zaradi katere se zaustavi tok programa.

Datoteko je najbolje zapreti z uporabo withstavka. To zagotavlja, da je datoteka zaprta, ko withizstopi blok znotraj stavka.

close()Metode nam ni treba izrecno poklicati . To se izvaja interno.

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

Pisanje v datoteke v Pythonu

Če želite zapisovati v datoteko v Pythonu, jo moramo odpreti v načinu pisanja w, dodajanja aali izključnega ustvarjanja x.

Pri wnačinu moramo biti previdni , saj se bo zapisal v datoteko, če že obstaja. Zaradi tega so vsi prejšnji podatki izbrisani.

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) V datoteko zapiše niz s in vrne število zapisanih znakov.
pisalne črte (vrstice) V datoteko zapiše seznam vrstic.

Zanimive Članki...