Viết Ghi File Text Trong Python

Viết File Text Trong Python

Tóm tắt:

  • Mở file
  • Viết file
  • Đóng file (bỏ qua cách này nếu dùng hàm with)
    • Ví dụ:
      • with open(“example.txt”, “w”) as f:
              f.write(“Hello world!”)

1. Mở file:

  • Cú pháp: open(path_to_a_file, mode)
    • path_to_a_file: là đường dẫn đến tệp bạn muốn mở. Nếu không tìm thấy tệp nào, một tệp mới sẽ được tạo.
    • mode:
      • w: viết dữ liệu vào file.
      • a: thêm dữ liệu vào cuối file.

2. Viết file:

  • Ví dụ phương thức write():
    • words = [“This “, “is “, “a “, “test”]
      with open (“example.txt”, “w”) as f:
            for word in words:
            f.write(word)

      => Output:This is a test

Nếu bạn muốn mỗi từ xuất hiện trên một dòng riêng biệt, hãy viết ký tự ngắt dòng ‘\n‘ sau khi ghi một chuỗi vào tệp.

  • words = [“This”, “is”, “a”, “test”]
    with open(“example.txt”, “w”) as f:
    for word in words:
    f.write(word)
    f.write(“\n”)

    => Output: 
    This
    is
    a
    test

  • Ví dụ phương thức writelines():

words = [“This “, “is “, “a “, “test”]

withopen(“example.txt”, “w”)as f:

      f.writelines(words)

=> Output: Sau khi chạy đoạn mã này, tệp example.txt trông như thế này:
This is a test

3. Cách nối vào tệp trong Python:

  • Để thêm văn bản vào cuối tệp sau các dòng văn bản hiện có, hãy sử dụng chế độ ghi ‘a‘.
  • Ví dụ:
    • # Let’s first write to a file
      with open(“example2.txt”, “w”) as f:
      f.write(“This is “
      )

      # Then let’s reopen the file and append some text to it:
      with open(“example2.txt”, “a”) as f:
      f.write(“just another test.”)

      => Output: Ở đây kết quả là một tệp có tên example2.txt với nội dung như sau:
      This is just another test.

Bài viết có tham khảo: cảm ơn tác giả!