Python-fil I / O: läs och skriv filer i Python

I den här handledningen lär du dig om Python-filhantering. Mer specifikt, öppna en fil, läsa från den, skriva in den, stänga den och olika filmetoder som du bör vara medveten om.

Video: Läsa och skriva filer i Python

Filer

Filerna heter platser på disken för att lagra relaterad information. De används för att permanent lagra data i ett icke-flyktigt minne (t.ex. hårddisk).

Eftersom RAM (Random Access Memory) är flyktigt (vilket förlorar sina data när datorn stängs av) använder vi filer för framtida användning av data genom att lagra dem permanent.

När vi vill läsa från eller skriva till en fil måste vi öppna den först. När vi är klara måste den stängas så att resurserna som är knutna till filen frigörs.

Därför sker i Python en filåtgärd i följande ordning:

  1. Öppna en fil
  2. Läs eller skriv (utför operation)
  3. Stäng filen

Öppna filer i Python

Python har en inbyggd open()funktion för att öppna en fil. Denna funktion returnerar ett filobjekt, även kallat ett handtag, eftersom det används för att läsa eller ändra filen i enlighet därmed.

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

Vi kan ange läget när vi öppnar en fil. I läge anger vi om vi vill läsa r, skriva weller lägga atill filen. Vi kan också ange om vi vill öppna filen i textläge eller binärt läge.

Standard är läsning i textläge. I det här läget får vi strängar när vi läser från filen.

Å andra sidan returnerar binärt läge byte och detta är det läge som ska användas vid hantering av icke-textfiler som bilder eller körbara filer.

Läge Beskrivning
r Öppnar en fil för läsning. (standard)
w Öppnar en fil för skrivning. Skapar en ny fil om den inte finns eller trunkerar filen om den finns.
x Öppnar en fil för exklusiv skapelse. Om filen redan finns misslyckas åtgärden.
a Öppnar en fil för att läggas till i slutet av filen utan att trunka den. Skapar en ny fil om den inte finns.
t Öppnas i textläge. (standard)
b Öppnas i binärt läge.
+ Öppnar en fil för uppdatering (läsning och skrivning)
 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

Till skillnad från andra språk aantyder tecknet inte siffran 97 förrän den kodas med ASCII(eller andra motsvarande kodningar).

Dessutom är standardkodningen plattformsberoende. I Windows är det cp1252bara utf-8i Linux.

Så vi får inte heller lita på standardkodningen, annars kommer vår kod att fungera annorlunda på olika plattformar.

Därför, när du arbetar med filer i textläge, rekommenderas det starkt att ange kodningstypen.

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

Stänga filer i Python

När vi är klara med att utföra åtgärder på filen, måste vi stänga filen ordentligt.

När du stänger en fil frigörs de resurser som var knutna till filen. Det görs med den close()metod som finns i Python.

Python har en skräpsamlare för att städa upp objekt utan referens men vi får inte lita på att den stänger filen.

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

Denna metod är inte helt säker. Om ett undantag inträffar när vi utför någon åtgärd med filen avslutas koden utan att stänga filen.

Ett säkrare sätt är att använda ett försök … äntligen blockera.

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

På detta sätt garanterar vi att filen stängs ordentligt även om ett undantag tas upp som får programflödet att stoppa.

Det bästa sättet att stänga en fil är att använda withuttalandet. Detta säkerställer att filen stängs när blocket inuti withuttalandet avslutas.

Vi behöver inte uttryckligen anropa close()metoden. Det görs internt.

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

Skriva till filer i Python

För att kunna skriva in en fil i Python måste vi öppna den i skriv- w, lägg till aeller exklusivt skapande xläge.

Vi måste vara försiktiga med wläget, eftersom det skrivs över i filen om det redan finns. På grund av detta raderas alla tidigare 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) Skriver strängarna till filen och returnerar antalet skrivna tecken.
skrivlinjer (linjer) Skriver en lista med rader till filen.

Intressanta artiklar...