Hướng dẫn how do you read all data from a text file in python? - làm thế nào để bạn đọc tất cả dữ liệu từ một tệp văn bản trong python?

Bạn đang ở đây: Trang chủ/ Python/ Làm thế nào để đọc toàn bộ tệp văn bản trong Python?Home / Python / How to read entire text file in Python?

Ngày 5 tháng 1 năm 2018 bởi cmdlinetipscmdlinetips

Thông thường người ta có thể cần đọc toàn bộ nội dung của tệp văn bản (hoặc tệp phẳng) cùng một lúc trong Python. Trong bài đăng này, chúng tôi đã cho thấy một ví dụ về việc đọc toàn bộ tệp và đọc từng dòng tệp văn bản. Dưới đây là một cách khác để nhập toàn bộ nội dung của tệp văn bản.

# Open a file: file
file = open('my_text_file',mode='r')

# read all lines at once
all_of_it = file.read()

# close the file
file.close()

Bài viết liên quan:

Ngày 18 tháng 4 năm 2022

Hướng dẫn how do you read all data from a text file in python? - làm thế nào để bạn đọc tất cả dữ liệu từ một tệp văn bản trong python?

Đọc các tập tin với Python

Các tệp ở khắp mọi nơi: trên máy tính, thiết bị di động và trên đám mây. Làm việc với các tệp là điều cần thiết cho mọi lập trình viên, bất kể ngôn ngữ lập trình nào mà bạn sử dụng.

Xử lý tệp là một cơ chế để tạo tệp, ghi dữ liệu và đọc dữ liệu từ nó. Tin tốt là Python được làm phong phú với các gói để xử lý các loại tệp khác nhau.

Trong hướng dẫn này, chúng tôi sẽ học cách xử lý các tệp thuộc các loại khác nhau. Tuy nhiên, chúng tôi sẽ tập trung nhiều hơn vào việc đọc các tệp với Python.

Sau khi bạn hoàn thành hướng dẫn này, bạn sẽ biết cách làm như sau:

  • Mở tệp và sử dụng Trình quản lý bối cảnh
    with open('zen_of_python.txt') as f:
        print(f.read())
    5
  • Chế độ tập tin trong Python
  • Đọc văn bản
  • Đọc tệp CSV
  • Đọc các tập tin JSON

Hãy để lặn trong.

Mở một tập tin

Trước khi truy cập nội dung của một tệp, chúng ta cần mở tệp. Python cung cấp một chức năng tích hợp giúp chúng tôi mở các tệp ở các chế độ khác nhau. Hàm

with open('zen_of_python.txt') as f:
    print(f.read())
6 chấp nhận hai tham số cần thiết: tên tệp và chế độ; Chế độ mặc định là
with open('zen_of_python.txt') as f:
    print(f.read())
7, chỉ mở tệp để đọc. Các chế độ xác định cách chúng ta có thể truy cập một tệp và cách chúng ta có thể thao tác nội dung của nó. Hàm
with open('zen_of_python.txt') as f:
    print(f.read())
6 cung cấp một vài chế độ khác nhau mà chúng tôi sẽ thảo luận sau trong hướng dẫn này.

Đầu tiên, hãy để thử chức năng bằng cách mở một tệp văn bản. Tải xuống tệp văn bản chứa Zen of Python và lưu trữ nó trong cùng một đường dẫn với mã của bạn.

f = open('zen_of_python.txt', 'r')
print(f.read())
f.close()
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!

Trong mã trên, hàm

with open('zen_of_python.txt') as f:
    print(f.read())
6 mở tệp văn bản ở chế độ đọc, cho phép chúng tôi lấy thông tin từ tệp mà không vô tình thay đổi nó. Trong dòng đầu tiên, đầu ra của hàm
with open('zen_of_python.txt') as f:
    print(f.read())
6 được gán cho biến
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
1, một đối tượng đại diện cho tệp văn bản. Trong dòng thứ hai của mã ở trên, chúng tôi sử dụng phương thức
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
2 để đọc toàn bộ tệp và in nội dung của nó. Phương thức
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
3 đóng tệp trong dòng cuối cùng. Chúng tôi phải luôn đóng các tệp đã mở sau khi chúng tôi hoàn thành chúng để phát hành tài nguyên máy tính của mình và tránh nêu ra các ngoại lệ.

Trong Python, chúng tôi có thể sử dụng Trình quản lý bối cảnh

with open('zen_of_python.txt') as f:
    print(f.read())
5 để đảm bảo chương trình phát hành các tài nguyên được sử dụng sau khi tệp được đóng, ngay cả khi xảy ra ngoại lệ. Hãy thử nó:

with open('zen_of_python.txt') as f:
    print(f.read())
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!

Mã trên tạo ra một bối cảnh bằng cách sử dụng câu lệnh

with open('zen_of_python.txt') as f:
    print(f.read())
5 rằng đối tượng tệp không còn mở ra khỏi ngữ cảnh. Biến ràng buộc,
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
1, đại diện cho đối tượng tệp mà tất cả các phương thức đối tượng tệp có thể truy cập được thông qua biến. Phương thức
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
2 đọc toàn bộ tệp trong dòng thứ hai và sau đó hàm
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
8 xuất ra nội dung tệp.

Khi chương trình đi đến cuối bối cảnh khối câu lệnh

with open('zen_of_python.txt') as f:
    print(f.read())
5, nó sẽ đóng tệp để phát hành tài nguyên và đảm bảo rằng các chương trình khác có thể sử dụng chúng. Nói chung, sử dụng câu lệnh
with open('zen_of_python.txt') as f:
    print(f.read())
5 là một thông lệ rất được khuyến khích khi bạn làm việc với các đối tượng cần được đóng ngay khi chúng không còn cần thiết, chẳng hạn như tệp, cơ sở dữ liệu và kết nối mạng.

Lưu ý rằng chúng tôi có quyền truy cập vào biến

    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
1 ngay cả sau khi thoát khỏi khối Trình quản lý bối cảnh
with open('zen_of_python.txt') as f:
    print(f.read())
5; Tuy nhiên, tập tin được đóng. Hãy để thử một số thuộc tính đối tượng tệp để xem biến có còn tồn tại và có thể truy cập không:

print("Filename is '{}'.".format(f.name))
if f.closed:
    print("File is closed.")
else:
    print("File isn't closed.")
    Filename is 'zen_of_python.txt'.
    File is closed.

Tuy nhiên, nó không thể đọc được từ tệp hoặc ghi vào tệp. Khi một tệp được đóng, mọi nỗ lực truy cập nội dung của nó sẽ dẫn đến lỗi sau:

f.read()
    ---------------------------------------------------------------------------

    ValueError                                Traceback (most recent call last)

    ~\AppData\Local\Temp/ipykernel_9828/3059900045.py in 
    ----> 1 f.read()

    ValueError: I/O operation on closed file.

Chế độ tập tin trong Python

Như chúng tôi đã đề cập trong phần trước, chúng tôi cần chỉ định chế độ trong khi mở tệp. Bảng sau đây hiển thị các chế độ tệp khác nhau trong Python:

Cách thứcSự mô tả
with open('zen_of_python.txt') as f:
    print(f.read())
7
Nó mở một tập tin chỉ để đọc.
print("Filename is '{}'.".format(f.name))
if f.closed:
    print("File is closed.")
else:
    print("File isn't closed.")
4
Nó mở một tập tin để viết. Nếu tệp tồn tại, nó sẽ ghi đè lên nó, nếu không, nó sẽ tạo một tệp mới.
print("Filename is '{}'.".format(f.name))
if f.closed:
    print("File is closed.")
else:
    print("File isn't closed.")
5
Nó chỉ mở một tập tin để nối thêm. Nếu tệp không tồn tại, nó sẽ tạo ra tệp.
print("Filename is '{}'.".format(f.name))
if f.closed:
    print("File is closed.")
else:
    print("File isn't closed.")
6
Nó tạo ra một tập tin mới. Nếu tập tin tồn tại, nó không thành công.
print("Filename is '{}'.".format(f.name))
if f.closed:
    print("File is closed.")
else:
    print("File isn't closed.")
7
Nó mở một tập tin để cập nhật.

Chúng tôi cũng có thể chỉ định mở một tệp ở chế độ văn bản,

print("Filename is '{}'.".format(f.name))
if f.closed:
    print("File is closed.")
else:
    print("File isn't closed.")
8, chế độ mặc định hoặc chế độ nhị phân,
print("Filename is '{}'.".format(f.name))
if f.closed:
    print("File is closed.")
else:
    print("File isn't closed.")
9. Hãy để xem cách chúng ta có thể sao chép một tệp hình ảnh, dataquest_logo.png, sử dụng các câu lệnh đơn giản:

with open('dataquest_logo.png', 'rb') as rf:
    with open('data_quest_logo_copy.png', 'wb') as wf:
        for b in rf:
            wf.write(b)

Mã trên sao chép hình ảnh logo DataQuest và lưu trữ nó trong cùng một đường dẫn. Chế độ

    Filename is 'zen_of_python.txt'.
    File is closed.
0 mở tệp để đọc ở chế độ nhị phân và chế độ
    Filename is 'zen_of_python.txt'.
    File is closed.
1 mở tệp để viết ở chế độ văn bản.

Đọc tệp văn bản

Có nhiều cách khác nhau để đọc tệp văn bản. Phần này sẽ xem xét một số phương pháp hữu ích để đọc nội dung của các tệp văn bản.

Cho đến nay, chúng tôi đã học được toàn bộ nội dung của một tệp có thể được đọc bằng phương pháp

    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
2. Điều gì sẽ xảy ra nếu chúng ta chỉ muốn đọc một vài byte từ một tệp văn bản. Để làm điều đó, chỉ định số byte trong phương thức
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
2. Hãy thử nó:

f = open('zen_of_python.txt', 'r')
print(f.read())
f.close()
0
f = open('zen_of_python.txt', 'r')
print(f.read())
f.close()
1

Mã đơn giản ở trên đọc 17 byte đầu tiên của tệp zen_of_python.txt và in chúng ra.

Đôi khi, việc đọc nội dung của tệp văn bản một dòng tại một thời điểm có ý nghĩa hơn. Trong trường hợp này, chúng ta có thể sử dụng phương pháp

    Filename is 'zen_of_python.txt'.
    File is closed.
4. Hãy làm nó:

f = open('zen_of_python.txt', 'r')
print(f.read())
f.close()
2
f = open('zen_of_python.txt', 'r')
print(f.read())
f.close()
3

Mã trên trả về dòng đầu tiên của tệp. Nếu chúng ta gọi phương thức thêm một lần nữa, nó sẽ trả về dòng thứ hai trong tệp, v.v., như sau:

f = open('zen_of_python.txt', 'r')
print(f.read())
f.close()
4
f = open('zen_of_python.txt', 'r')
print(f.read())
f.close()
5

Phương pháp hữu ích này giúp chúng tôi đọc toàn bộ tệp tăng dần. Mã sau đây xuất ra toàn bộ tệp bằng cách lặp qua dòng nó cho đến khi con trỏ tệp theo dõi nơi chúng tôi đọc hoặc viết tệp đến cuối tệp. Khi phương thức

    Filename is 'zen_of_python.txt'.
    File is closed.
4 đi đến cuối tệp, nó sẽ trả về một chuỗi trống, ________ 66.with Open (‘zen_of_python.txt,) như f:

f = open('zen_of_python.txt', 'r')
print(f.read())
f.close()
6
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!

Mã trên đọc dòng đầu tiên của tệp bên ngoài vòng lặp và gán nó cho biến

    Filename is 'zen_of_python.txt'.
    File is closed.
7. Bên trong vòng lặp trong khi nó in chuỗi được lưu trữ trong biến
    Filename is 'zen_of_python.txt'.
    File is closed.
7, sau đó đọc dòng tiếp theo của tệp. Vòng lặp trong khi lặp lại quá trình cho đến khi phương thức
    Filename is 'zen_of_python.txt'.
    File is closed.
4 trả về một chuỗi trống. Chuỗi trống đánh giá thành
f.read()
0 trong vòng lặp, do đó quá trình lặp lại chấm dứt.

Phương pháp hữu ích khác để đọc tệp văn bản là phương thức

f.read()
1. Áp dụng phương thức này trên một đối tượng tệp Trả về danh sách các chuỗi chứa từng dòng của tệp. Hãy để xem cách thức hoạt động của nó:

f = open('zen_of_python.txt', 'r')
print(f.read())
f.close()
8

Hãy để kiểm tra kiểu dữ liệu của biến

f.read()
2 và sau đó in nó:

f = open('zen_of_python.txt', 'r')
print(f.read())
f.close()
9
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
0

Nó có một danh sách các chuỗi trong đó mỗi mục trong danh sách là một dòng của tệp văn bản. Nhân vật thoát

f.read()
3 đại diện cho một dòng mới trong tệp. Ngoài ra, chúng tôi có thể truy cập mọi mục trong danh sách bằng cách lập chỉ mục hoặc cắt các hoạt động:

    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
1
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
2

Đọc các tập tin CSV

Cho đến nay, chúng tôi đã học được cách làm việc với các tệp văn bản thông thường. Tuy nhiên, đôi khi dữ liệu có định dạng CSV và nó phổ biến cho các chuyên gia dữ liệu để truy xuất thông tin cần thiết và thao tác nội dung của các tệp CSV.

Chúng tôi sẽ sử dụng mô -đun CSV trong phần này. Mô-đun CSV cung cấp các phương pháp hữu ích để đọc các giá trị được phân tách bằng dấu phẩy được lưu trữ trong tệp CSV. Chúng tôi sẽ thử nó ngay bây giờ, nhưng trước tiên, bạn cần tải xuống tệp

f.read()
4 và lưu trữ nó trong thư mục làm việc hiện tại:

    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
3
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
4

Mỗi hàng của tệp CSV tạo thành một danh sách trong đó mọi mục có thể dễ dàng truy cập, như sau:

    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
5
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
6

Nó có thể sử dụng tên của các cột thay vì sử dụng các chỉ số của chúng, thường thuận tiện hơn cho các nhà phát triển. Trong trường hợp này, thay vì sử dụng phương pháp

f.read()
5, chúng tôi sử dụng phương thức
f.read()
6 trả về một tập hợp các đối tượng từ điển. Hãy thử nó:

    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
7
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
8

Đọc các tập tin JSON

Một định dạng tệp phổ biến khác mà chúng tôi chủ yếu sử dụng để lưu trữ và trao đổi dữ liệu là JSON. JSON là viết tắt của ký hiệu đối tượng JavaScript và nó cho phép chúng tôi lưu trữ dữ liệu với các cặp giá trị khóa được phân tách bằng dấu phẩy.

Trong phần này, chúng tôi sẽ tải một tệp JSON và làm việc với nó dưới dạng đối tượng JSON - không phải là tệp văn bản. Để làm điều đó, chúng tôi cần nhập mô -đun JSON. Sau đó, trong Trình quản lý bối cảnh

with open('zen_of_python.txt') as f:
    print(f.read())
5, chúng tôi sử dụng phương thức
f.read()
8 thuộc về đối tượng
f.read()
9. Nó tải nội dung tệp và lưu trữ nó trong biến
    ---------------------------------------------------------------------------

    ValueError                                Traceback (most recent call last)

    ~\AppData\Local\Temp/ipykernel_9828/3059900045.py in 
    ----> 1 f.read()

    ValueError: I/O operation on closed file.
0 dưới dạng từ điển. Hãy để thử nó, nhưng trước khi chạy mã, hãy tải xuống tệp
    ---------------------------------------------------------------------------

    ValueError                                Traceback (most recent call last)

    ~\AppData\Local\Temp/ipykernel_9828/3059900045.py in 
    ----> 1 f.read()

    ValueError: I/O operation on closed file.
1 và đưa nó vào thư mục làm việc hiện tại.

    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
9
with open('zen_of_python.txt') as f:
    print(f.read())
0

Hãy để kiểm tra kiểu dữ liệu của biến

    ---------------------------------------------------------------------------

    ValueError                                Traceback (most recent call last)

    ~\AppData\Local\Temp/ipykernel_9828/3059900045.py in 
    ----> 1 f.read()

    ValueError: I/O operation on closed file.
2:

with open('zen_of_python.txt') as f:
    print(f.read())
1
with open('zen_of_python.txt') as f:
    print(f.read())
2

Kiểu dữ liệu của nó là một từ điển. Vì vậy, chúng tôi có thể truy cập từng mẩu thông tin được lưu trữ trong tệp JSON với khóa của nó. Hãy để xem cách chúng ta có thể lấy dữ liệu từ nó:

with open('zen_of_python.txt') as f:
    print(f.read())
3
with open('zen_of_python.txt') as f:
    print(f.read())
4

Sự kết luận

Hướng dẫn này đã thảo luận về việc xử lý tệp trong Python, tập trung vào việc đọc nội dung của các tệp. Bạn đã tìm hiểu về chức năng tích hợp mở (), với trình quản lý bối cảnh và cách đọc các loại tệp phổ biến như văn bản, CSV và JSON.