I / O tệp Python: Đọc và ghi tệp bằng Python

Trong hướng dẫn này, bạn sẽ tìm hiểu về các thao tác với tệp Python. Cụ thể hơn, mở một tệp, đọc từ đó, ghi vào tệp, đóng tệp và các phương thức tệp khác nhau mà bạn nên biết.

Video: Đọc và ghi tệp bằng Python

Các tập tin

Các tệp được đặt tên các vị trí trên đĩa để lưu trữ thông tin liên quan. Chúng được sử dụng để lưu trữ vĩnh viễn dữ liệu trong một bộ nhớ không bay hơi (ví dụ: đĩa cứng).

Vì Bộ nhớ truy cập ngẫu nhiên (RAM) dễ bay hơi (mất dữ liệu khi máy tính tắt), chúng tôi sử dụng tệp để sử dụng dữ liệu trong tương lai bằng cách lưu trữ vĩnh viễn chúng.

Khi chúng ta muốn đọc hoặc ghi vào một tập tin, trước tiên chúng ta cần mở nó. Khi chúng ta hoàn tất, nó cần phải được đóng lại để các tài nguyên gắn với tệp được giải phóng.

Do đó, trong Python, hoạt động tệp diễn ra theo thứ tự sau:

  1. Mở tệp tin
  2. Đọc hoặc ghi (thực hiện thao tác)
  3. Đóng tệp

Mở tệp bằng Python

Python có một open()chức năng tích hợp để mở tệp. Hàm này trả về một đối tượng tệp, còn được gọi là một xử lý, vì nó được sử dụng để đọc hoặc sửa đổi tệp cho phù hợp.

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

Chúng tôi có thể chỉ định chế độ trong khi mở tệp. Trong chế độ, chúng tôi chỉ định xem chúng tôi muốn đọc r, ghi whay nối thêm avào tệp. Chúng tôi cũng có thể chỉ định xem chúng tôi muốn mở tệp ở chế độ văn bản hay chế độ nhị phân.

Mặc định là đọc ở chế độ văn bản. Trong chế độ này, chúng tôi nhận được chuỗi khi đọc từ tệp.

Mặt khác, chế độ nhị phân trả về byte và đây là chế độ được sử dụng khi xử lý các tệp không phải văn bản như hình ảnh hoặc tệp thực thi.

Chế độ Sự miêu tả
r Mở tệp để đọc. (mặc định)
w Mở tệp để viết. Tạo một tệp mới nếu nó không tồn tại hoặc cắt bớt tệp nếu nó tồn tại.
x Mở tệp để tạo độc quyền. Nếu tệp đã tồn tại, hoạt động không thành công.
a Mở tệp để thêm vào cuối tệp mà không cắt bớt. Tạo một tệp mới nếu nó không tồn tại.
t Mở ở chế độ văn bản. (mặc định)
b Mở ở chế độ nhị phân.
+ Mở tệp để cập nhật (đọc và ghi)
 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

Không giống như các ngôn ngữ khác, ký tự akhông bao hàm số 97 cho đến khi nó được mã hóa bằng ASCII(hoặc các mã hóa tương đương khác).

Hơn nữa, mã hóa mặc định phụ thuộc vào nền tảng. Trong windows, nó là cp1252nhưng utf-8trong Linux.

Vì vậy, chúng ta cũng không được dựa vào bảng mã mặc định nếu không mã của chúng ta sẽ hoạt động khác nhau trong các nền tảng khác nhau.

Do đó, khi làm việc với các tệp ở chế độ văn bản, bạn nên chỉ định kiểu mã hóa.

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

Đóng tệp bằng Python

Khi thực hiện xong các thao tác trên tệp, chúng ta cần đóng tệp đúng cách.

Việc đóng tệp sẽ giải phóng tài nguyên được gắn với tệp. Nó được thực hiện bằng cách sử dụng close()phương pháp có sẵn trong Python.

Python có một trình thu gom rác để dọn dẹp các đối tượng không được tham chiếu nhưng chúng ta không được dựa vào nó để đóng tệp.

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

Phương pháp này không hoàn toàn an toàn. Nếu một ngoại lệ xảy ra khi chúng tôi đang thực hiện một số thao tác với tệp, thì mã sẽ thoát mà không đóng tệp.

Một cách an toàn hơn là sử dụng một khối thử… cuối cùng.

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

Bằng cách này, chúng tôi đảm bảo rằng tệp được đóng đúng cách ngay cả khi một ngoại lệ được đưa ra khiến luồng chương trình dừng lại.

Cách tốt nhất để đóng tệp là sử dụng withcâu lệnh. Điều này đảm bảo rằng tệp được đóng khi khối bên trong withcâu lệnh được thoát.

Chúng ta không cần gọi close()phương thức một cách rõ ràng . Nó được thực hiện trong nội bộ.

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

Ghi vào tệp bằng Python

Để ghi vào một tệp bằng Python, chúng ta cần mở nó ở chế độ ghi w, nối thêm ahoặc xchế độ tạo độc quyền .

Chúng ta cần phải cẩn thận với wchế độ này, vì nó sẽ ghi đè lên tệp nếu nó đã tồn tại. Do đó, tất cả dữ liệu trước đó sẽ bị xóa.

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) Ghi chuỗi s vào tệp và trả về số ký tự được ghi.
writelines (dòng) Ghi danh sách các dòng vào tệp.

thú vị bài viết...