Thao tác với tệp trong python

Chúng ta thường lưu trữ dữ liệu của mình dưới các định dạng file khác nhau như .txt, .json, .xml, .csv, .tsv, .xlsx). Trong phần này, ta sẽ làm quen với cách xử lý file (tệp tin) trong python. Đầu tiên, chúng ta hãy làm quen với việc xử lý các file có định dạng phổ biến nhất là .txt

Show

    Xử lý file là một phần không thể thiếu khi lập trình, đôi lúc bạn sẽ phải thực hiện các thao tác như tạo file, đọc file, cập nhật file và xóa file. Trong python mở một tệp tin để xử lý dữ liệu chúng ta sẽ sử dụng hàm được tích hợp sẵn

    # Syntax
    open('filename', mode)
    # mode(r, a, w, x, t,b) là các chế độ như đọc, ghi, xóa,...

    • Một số chế độ (mode) xử lý để làm việc với file trong python:
      • f = open('./files/reading_file_example.txt')
        txt = f.read()
        print(type(txt))
        print(txt)
        f.close()
         
        # output
        # 
        # This is an example to show how to open a file and read.
        # This is the second line of the text.
        3 - Read - Giá trị mặc định. Mở tệp để đọc, lỗi nếu tệp không tồn tại.
      • f = open('./files/reading_file_example.txt')
        txt = f.read()
        print(type(txt))
        print(txt)
        f.close()
         
        # output
        # 
        # This is an example to show how to open a file and read.
        # This is the second line of the text.
        4 - Append - Mở tệp để nối thêm (cập nhật thêm), tự tạo tệp nếu tệp đó không tồn tại.
      • f = open('./files/reading_file_example.txt')
        txt = f.read()
        print(type(txt))
        print(txt)
        f.close()
         
        # output
        # 
        # This is an example to show how to open a file and read.
        # This is the second line of the text.
        5 - Write - Mở tệp để ghi, tạo tệp nếu tệp đó không tồn tại.
      • f = open('./files/reading_file_example.txt')
        txt = f.read()
        print(type(txt))
        print(txt)
        f.close()
         
        # output
        # 
        # This is an example to show how to open a file and read.
        # This is the second line of the text.
        6 - Create - Tạo tệp được chỉ định, trả về lỗi nếu tệp tồn tại.
      • f = open('./files/reading_file_example.txt')
        txt = f.read()
        print(type(txt))
        print(txt)
        f.close()
         
        # output
        # 
        # This is an example to show how to open a file and read.
        # This is the second line of the text.
        7 - Text - Chế độ văn bản (Giá trị mặc định).
      • f = open('./files/reading_file_example.txt')
        txt = f.read()
        print(type(txt))
        print(txt)
        f.close()
         
        # output
        # 
        # This is an example to show how to open a file and read.
        # This is the second line of the text.
        8 - Binary - Chế độ nhị phân (ví dụ: hình ảnh).
      • f = open('./files/reading_file_example.txt')
        txt = f.read()
        print(type(txt))
        print(txt)
        f.close()
         
        # output
        # 
        # This is an example to show how to open a file and read.
        # This is the second line of the text.
        9 - Mở tệp để cập nhật (đọc và ghi).

    Bạn cũng nên xem thêm phần mà tôi đã giới thiệu ở phần nhập xuất dữ liệu để hiểu rõ hơn.

    Chế độ mở mặc định là đọc, vì vậy chúng ta không chỉ định

    f = open('./files/reading_file_example.txt')
    txt = f.read()
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an example to show how to open a file and read.
    # This is the second line of the text.
    3 hoặc
    f = open('./files/reading_file_example.txt')
    txt = f.read(10)
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an
    1. Như vậy, bạn đã tạo và lưu một file có tên là read_file_example.txt trong thư mục. Hãy xem đoạn code dưới đây hoạt động như thế nào:

    f = open('./files/reading_file_example.txt')
    print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'>

    Như bạn có thể thấy trong ví dụ trên, bạn đã print tệp đã mở và nó hiển thị cho bạn một số thông tin về tệp đó. Tệp được mở có các phương thức đọc khác nhau như:

    f = open('./files/reading_file_example.txt')
    txt = f.read(10)
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an
    2,
    f = open('./files/reading_file_example.txt')
    txt = f.read(10)
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an
    3
    ,
    f = open('./files/reading_file_example.txt')
    txt = f.read(10)
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an
    4
    . Một tệp đã mở phải được đóng bằng phương thức
    f = open('./files/reading_file_example.txt')
    txt = f.read(10)
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an
    5
    .

    Đọc toàn bộ nội dung dưới dạng chuỗi (xem lại bài viết về string trong python). Nếu chúng ta muốn giới hạn số ký tự mà chúng ta đọc, bạn có thể giới hạn nó bằng .

    f = open('./files/reading_file_example.txt')
    txt = f.read()
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an example to show how to open a file and read.
    # This is the second line of the text.

    Thay vì hiển thị tất cả nội dung, chúng ta hãy lấy ra 10 ký tự đầu tiên của file.

    f = open('./files/reading_file_example.txt')
    txt = f.read(10)
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an

    Phương thức này chỉ sẽ trả về kết quả của dòng đầu tiên

    f = open('./files/reading_file_example.txt')
    line = f.readline()
    print(type(line))
    print(line)
    f.close()
     
    # output
    # 
    # This is an example to show how to open a file and read.

    Phương thức này sẽ đọc tất cả các dòng có trong tệp và trả về một list (mỗi dòng là một phần tử của list)

    f = open('./files/reading_file_example.txt')
    lines = f.readlines()
    print(type(lines))
    print(lines)
    f.close()
     
    # output
    # 
    # ['This is an example to show how to open a file and read.\n', 'This is the second line of the text.']

    Ngoài ra, Một cách khác để lấy tất cả các dòng trong file để đưa vào list ta có thể sử dụng phương thức

    f = open('./files/reading_file_example.txt')
    txt = f.read(10)
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an
    6

    f = open('./files/reading_file_example.txt')
    lines = f.read().splitlines()
    print(type(lines))
    print(lines)
    f.close()
     
    # output
    # 
    # ['This is an example to show how to open a file and read.', 'This is the second line of the text.']

    Sau khi mở một tệp, phần lớn chúng ta thường quên sử dụng

    f = open('./files/reading_file_example.txt')
    txt = f.read(10)
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an
    5 để đóng file lại. Python cung cấp cho bạn một phương thức with bạn có thể sử dụng nó nếu bạn thường xuyên quên đóng file bằng
    f = open('./files/reading_file_example.txt')
    txt = f.read(10)
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an
    5
    . Hãy viết lại ví dụ trước trên phương thức with như sau:

    with open('./files/reading_file_example.txt') as f:
        lines = f.read().splitlines()
        print(type(lines))
        print(lines)
     
    # output
    # 
    # ['This is an example to show how to open a file and read.', 'This is the second line of the text.']

    Để ghi vào một tệp hiện có, chúng ta phải thêm một chế độ làm tham số cho hàm

    f = open('./files/reading_file_example.txt')
    txt = f.read(10)
    print(type(txt))
    print(txt)
    f.close()
     
    # output
    # 
    # This is an
    9 như sau:

    • f = open('./files/reading_file_example.txt')
      txt = f.read()
      print(type(txt))
      print(txt)
      f.close()
       
      # output
      # 
      # This is an example to show how to open a file and read.
      # This is the second line of the text.
      4 - append - sẽ nối thêm vào cuối tệp, nếu tệp không tồn tại, nó sẽ báo FileNotFoundError.
    • f = open('./files/reading_file_example.txt')
      txt = f.read()
      print(type(txt))
      print(txt)
      f.close()
       
      # output
      # 
      # This is an example to show how to open a file and read.
      # This is the second line of the text.
      5 - write - sẽ ghi đè lên bất kỳ nội dung hiện có nào, nếu tệp không tồn tại thì nó sẽ tạo ra.

    Hãy nối một số nội dung vào tệp mà chúng ta đang đọc:

    with open('./files/reading_file_example.txt','a') as f:
        f.write('This text has to be appended at the end')

    Đoạn mã dưới đây sẽ tạo một tệp mới, nếu tệp không tồn tại:

    with open('./files/writing_file_example.txt','w') as f:
        f.write('This text will be written in a newly created file')

    Trong phần trước chúng ta đã biết . Tương tự, để xóa một tệp, chúng ta cũng .

    f = open('./files/reading_file_example.txt')
    print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'>
    0

    Nếu tệp không tồn tại, phương thức

    f = open('./files/reading_file_example.txt')
    line = f.readline()
    print(type(line))
    print(line)
    f.close()
     
    # output
    # 
    # This is an example to show how to open a file and read.
    2 sẽ gây ra lỗi, vì vậy tốt nhất là bạn nên sử dụng câu lệnh điều kiện như sau:

    f = open('./files/reading_file_example.txt')
    print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'>
    1

    Tệp có phần mở rộng .txt là một dạng dữ liệu rất phổ biến mà chúng ta đã trình bày trong phần trước (bạn có thể xem lại ). Hãy chuyển sang tệp JSON

    JSON là viết tắt của JavaScript Object Notation. Trên thực tế, đó là một đối tượng JavaScript được chuỗi hóa. Ví dụ:

    f = open('./files/reading_file_example.txt')
    print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'>
    2

    • Đổi từ JSON sang Dictionary: Để chuyển đổi một JSON thành một dictionary, trước tiên chúng ta sẽ import module json (xem lại cách sử dụng module trong python) và sau đó chúng ta sử dụng phương thức
      f = open('./files/reading_file_example.txt')
      line = f.readline()
      print(type(line))
      print(line)
      f.close()
       
      # output
      # 
      # This is an example to show how to open a file and read.
      3

    f = open('./files/reading_file_example.txt')
    print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'>
    3

    • Đổi từ Dictionary sang JSON: Để thay đổi Dictionary thành JSON, chúng ta sử dụng phương thức
      f = open('./files/reading_file_example.txt')
      line = f.readline()
      print(type(line))
      print(line)
      f.close()
       
      # output
      # 
      # This is an example to show how to open a file and read.
      4
      từ mô-đun json.

    f = open('./files/reading_file_example.txt')
    print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'>
    4

    • Lưu file dưới dạng tệp JSON: Chúng ta có thể lưu trữ dữ liệu của mình dưới dạng json. Hãy lưu nó bằng đoạn code sau:

    f = open('./files/reading_file_example.txt')
    print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'>
    5

    Trong đoạn code trên, chúng ta sử dụng encoding='utf-8' và indent=4 (thụt đầu dòng). Thụt lề giúp dễ đọc file json hơn.

    CSV là viết tắt của cụm từ Comma Separated Values (các giá trị được phân tách bằng dấu phẩy) mà ở phần trước chúng ta cũng đã tìm hiểu cơ bản . CSV là một định dạng tệp đơn giản được sử dụng để lưu trữ dữ liệu dưới dạng bảng, chẳng hạn như bảng tính hoặc cơ sở dữ liệu. CSV là một định dạng dữ liệu rất phổ biến trong data science.

    Ví dụ đây là nội dụng của file csv_example.csv

    f = open('./files/reading_file_example.txt')
    print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'>
    6

    Ví dụ:

    f = open('./files/reading_file_example.txt')
    print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'>
    7

    Để đọc các tệp excel, chúng ta cần cài đặt package có tên xlrd. Bạn cần tham khảo .

    XML là một định dạng dữ liệu có cấu trúc khác trông giống như HTML. Trong XML, các thẻ không được xác định trước. Dòng đầu tiên là dòng khai báo trong XML. Person là tags (thẻ) gốc của file XML dưới đây. Ví dụ về một file XML: