Fail Python I / O: Baca dan Tulis Fail di Python

Dalam tutorial ini, anda akan belajar mengenai operasi fail Python. Lebih khusus lagi, membuka fail, membaca daripadanya, menulis ke dalamnya, menutupnya, dan pelbagai kaedah fail yang harus anda perhatikan.

Video: Membaca dan Menulis Fail di Python

Fail

Fail dinamakan lokasi pada cakera untuk menyimpan maklumat yang berkaitan. Mereka digunakan untuk menyimpan data secara kekal dalam memori yang tidak mudah berubah (misalnya cakera keras).

Oleh kerana Memori Akses Rawak (RAM) tidak stabil (yang kehilangan datanya ketika komputer dimatikan), kami menggunakan fail untuk penggunaan data di masa depan dengan menyimpannya secara kekal.

Apabila kita mahu membaca dari atau menulis ke fail, kita perlu membukanya terlebih dahulu. Apabila kita selesai, ia perlu ditutup supaya sumber yang terikat dengan fail dibebaskan.

Oleh itu, di Python, operasi fail berlaku mengikut urutan berikut:

  1. Buka fail
  2. Baca atau tulis (laksanakan operasi)
  3. Tutup fail

Membuka Fail di Python

Python mempunyai fungsi terbina dalam open()untuk membuka fail. Fungsi ini mengembalikan objek file, juga disebut pegangan, karena digunakan untuk membaca atau mengubah file sesuai.

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

Kita boleh menentukan mod semasa membuka fail. Dalam mod, kita menentukan sama ada kita mahu membaca r, menulis watau menambah afail. Kami juga dapat menentukan sama ada kami mahu membuka fail dalam mod teks atau mod binari.

Lalai adalah membaca dalam mod teks. Dalam mod ini, kita mendapat rentetan ketika membaca dari fail.

Sebaliknya, mod binari mengembalikan bait dan ini adalah mod yang akan digunakan semasa berurusan dengan fail bukan teks seperti gambar atau fail yang boleh dilaksanakan.

Mod Penerangan
r Membuka fail untuk dibaca. (lalai)
w Membuka fail untuk ditulis. Membuat fail baru jika tidak ada atau memotong fail jika ada.
x Membuka fail untuk pembuatan eksklusif. Sekiranya fail sudah ada, operasi gagal.
a Membuka fail untuk ditambahkan pada akhir fail tanpa memotongnya. Membuat fail baru jika tidak ada.
t Dibuka dalam mod teks. (lalai)
b Dibuka dalam mod binari.
+ Membuka fail untuk dikemas kini (membaca dan menulis)
 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

Tidak seperti bahasa lain, watak atidak menyiratkan nombor 97 sehingga ia dikodkan menggunakan ASCII(atau pengekodan setara yang lain)

Selain itu, pengekodan lalai bergantung pada platform. Di tingkap, ia adalah cp1252tetapi utf-8dalam Linux.

Oleh itu, kita juga tidak boleh bergantung pada pengekodan lalai atau kod kita akan berkelakuan berbeza dalam platform yang berbeza.

Oleh itu, semasa bekerja dengan fail dalam mod teks, sangat disarankan untuk menentukan jenis pengekodan.

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

Fail Penutup di Python

Apabila kita selesai melakukan operasi pada fail, kita perlu menutup fail dengan betul.

Menutup fail akan membebaskan sumber daya yang terikat dengan fail. Ia dilakukan dengan menggunakan close()kaedah yang terdapat di Python.

Python mempunyai pengutip sampah untuk membersihkan objek yang tidak dirujuk tetapi kita tidak boleh bergantung padanya untuk menutup fail.

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

Kaedah ini tidak sepenuhnya selamat. Sekiranya pengecualian berlaku semasa kami melakukan beberapa operasi dengan fail, kod akan keluar tanpa menutup fail.

Cara yang lebih selamat adalah dengan mencuba… akhirnya menyekat.

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

Dengan cara ini, kami menjamin bahawa fail ditutup dengan betul walaupun terdapat pengecualian yang menyebabkan aliran program berhenti.

Cara terbaik untuk menutup fail adalah dengan menggunakan withpenyataan. Ini memastikan bahawa fail ditutup semasa blok di dalam withpenyataan keluar.

Kami tidak perlu memanggil close()kaedah tersebut secara eksplisit . Ia dilakukan secara dalaman.

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

Menulis ke Fail di Python

Untuk menulis ke dalam fail di Python, kita perlu membukanya dalam mod penulisan w, penambahan aatau penciptaan eksklusif x.

Kita harus berhati-hati dengan wmod, kerana akan menimpa ke fail jika sudah ada. Oleh kerana itu, semua data sebelumnya terhapus.

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) Menulis rentetan s ke fail dan mengembalikan bilangan watak yang ditulis.
garis panduan (garisan) Menulis senarai baris ke fail.

Artikel menarik...