Hướng dẫn how do you read text lines in python? - làm thế nào để bạn đọc các dòng văn bản trong python?

Để đọc một tệp vào danh sách, bạn cần phải làm ba điều:

  • Mở tập tin
  • Đọc tệp
  • Lưu trữ nội dung như danh sách

May mắn thay, Python làm cho nó rất dễ dàng để làm những việc này, vì vậy cách ngắn nhất để đọc tệp vào danh sách là:

lst = list(open(filename))

Tuy nhiên tôi sẽ thêm một số lời giải thích.

Mở tập tin

Tôi giả sử rằng bạn muốn mở một tệp cụ thể và bạn không giao dịch trực tiếp với tay cầm tệp (hoặc tay cầm giống như tệp). Chức năng được sử dụng phổ biến nhất để mở một tệp trong Python là

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
6, cần một đối số bắt buộc và hai đối số tùy chọn trong Python 2.7:

  • Tên tệp
  • Cách thức
  • Bộ đệm (tôi sẽ bỏ qua đối số này trong câu trả lời này)

Tên tệp phải là một chuỗi đại diện cho đường dẫn đến tệp. Ví dụ:

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)

Lưu ý rằng phần mở rộng tệp cần được chỉ định. Điều này đặc biệt quan trọng đối với người dùng Windows vì các phần mở rộng tệp như

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
7 hoặc
open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
8, v.v. được ẩn theo mặc định khi được xem trong Explorer.

Đối số thứ hai là

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
9, theo mặc định, có nghĩa là "chỉ đọc". Đó chính xác là những gì bạn cần trong trường hợp của bạn.

Nhưng trong trường hợp bạn thực sự muốn tạo một tệp và/hoặc ghi vào một tệp, bạn sẽ cần một đối số khác ở đây. Có một câu trả lời tuyệt vời nếu bạn muốn có một cái nhìn tổng quan.

Để đọc một tệp, bạn có thể bỏ qua

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
9 hoặc chuyển nó một cách rõ ràng:

open(filename)
open(filename, 'r')

Cả hai sẽ mở tệp ở chế độ chỉ đọc. Trong trường hợp bạn muốn đọc trong tệp nhị phân trên Windows, bạn cần sử dụng chế độ

open(filename)
open(filename, 'r')
2:

open(filename, 'rb')

Trên các nền tảng khác,

open(filename)
open(filename, 'r')
3 (chế độ nhị phân) chỉ đơn giản bị bỏ qua.


Bây giờ tôi đã chỉ ra cách

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
6 tệp, hãy nói về thực tế là bạn luôn cần phải
open(filename)
open(filename, 'r')
5. Nếu không, nó sẽ giữ một tay cầm tệp mở cho tệp cho đến khi quá trình thoát ra (hoặc Python rác xử lý tệp).

Trong khi bạn có thể sử dụng:

f = open(filename)
# ... do stuff with f
f.close()

Điều đó sẽ không đóng tệp khi một cái gì đó giữa

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
6 và
open(filename)
open(filename, 'r')
5 ném một ngoại lệ. Bạn có thể tránh điều đó bằng cách sử dụng
open(filename)
open(filename, 'r')
8 và
open(filename)
open(filename, 'r')
9:

f = open(filename)
# nothing in between!
try:
    # do stuff with f
finally:
    f.close()

Tuy nhiên, Python cung cấp các nhà quản lý bối cảnh có cú pháp đẹp hơn (nhưng đối với

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
6, nó gần giống với
open(filename)
open(filename, 'r')
8 và
open(filename)
open(filename, 'r')
9 ở trên):

with open(filename) as f:
    # do stuff with f
# The file is always closed after the with-scope ends.

Cách tiếp cận cuối cùng là cách tiếp cận được đề xuất để mở một tập tin trong Python!recommended approach to open a file in Python!

Đọc tập tin

Được rồi, bạn đã mở tệp, bây giờ làm thế nào để đọc nó?

Hàm

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
6 trả về một đối tượng
open(filename, 'rb')
4 và nó hỗ trợ giao thức lặp Pythons. Mỗi lần lặp sẽ cung cấp cho bạn một dòng:

with open(filename) as f:
    for line in f:
        print(line)

Điều này sẽ in từng dòng của tệp. Tuy nhiên, lưu ý rằng mỗi dòng sẽ chứa một ký tự mới

open(filename, 'rb')
5 ở cuối (bạn có thể muốn kiểm tra xem Python của bạn có được xây dựng với hỗ trợ Newlines Universal hay không - nếu không bạn cũng có thể có
open(filename, 'rb')
6 trên Windows hoặc
open(filename, 'rb')
7 trên Mac làm Newlines). Nếu bạn không muốn rằng bạn có thể chỉ cần xóa ký tự cuối cùng (hoặc hai ký tự cuối cùng trên Windows):

with open(filename) as f:
    for line in f:
        print(line[:-1])

Nhưng dòng cuối cùng không nhất thiết phải có một dòng mới, vì vậy người ta không nên sử dụng nó. Người ta có thể kiểm tra xem nó có kết thúc bằng một dòng mới hay không và nếu loại bỏ nó:

with open(filename) as f:
    for line in f:
        if line.endswith('\n'):
            line = line[:-1]
        print(line)

Nhưng bạn có thể chỉ cần loại bỏ tất cả các không gian trắng (bao gồm cả ký tự

open(filename, 'rb')
5) từ cuối chuỗi, điều này cũng sẽ loại bỏ tất cả các không gian trắng kéo dài khác để bạn phải cẩn thận nếu những điều này quan trọng:

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
0

Tuy nhiên, nếu các dòng kết thúc bằng

open(filename, 'rb')
6 (Windows "Newlines") rằng
f = open(filename)
# ... do stuff with f
f.close()
0 cũng sẽ chăm sóc
open(filename, 'rb')
7!

Lưu trữ nội dung như danh sách

May mắn thay, Python làm cho nó rất dễ dàng để làm những việc này, vì vậy cách ngắn nhất để đọc tệp vào danh sách là:

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
1

Tuy nhiên tôi sẽ thêm một số lời giải thích.

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
2

Mở tập tin

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
3

Tôi giả sử rằng bạn muốn mở một tệp cụ thể và bạn không giao dịch trực tiếp với tay cầm tệp (hoặc tay cầm giống như tệp). Chức năng được sử dụng phổ biến nhất để mở một tệp trong Python là

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
6, cần một đối số bắt buộc và hai đối số tùy chọn trong Python 2.7:

Tên tệp

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
4

or:

open('afile')   # opens the file named afile in the current working directory
open('adir/afile')            # relative path (relative to the current working directory)
open('C:/users/aname/afile')  # absolute path (windows)
open('/usr/local/afile')      # absolute path (linux)
5

Cách thức

Bộ đệm (tôi sẽ bỏ qua đối số này trong câu trả lời này)

  • Tên tệp phải là một chuỗi đại diện cho đường dẫn đến tệp. Ví dụ:
  • Lưu ý rằng phần mở rộng tệp cần được chỉ định. Điều này đặc biệt quan trọng đối với người dùng Windows vì các phần mở rộng tệp như
    open('afile')   # opens the file named afile in the current working directory
    open('adir/afile')            # relative path (relative to the current working directory)
    open('C:/users/aname/afile')  # absolute path (windows)
    open('/usr/local/afile')      # absolute path (linux)
    
    7 hoặc
    open('afile')   # opens the file named afile in the current working directory
    open('adir/afile')            # relative path (relative to the current working directory)
    open('C:/users/aname/afile')  # absolute path (windows)
    open('/usr/local/afile')      # absolute path (linux)
    
    8, v.v. được ẩn theo mặc định khi được xem trong Explorer.
  • Luôn duyệt tài liệu cho các chức năng/lớp có sẵn. Hầu hết thời gian có một trận đấu hoàn hảo cho nhiệm vụ hoặc ít nhất một hoặc hai người tốt. Lựa chọn rõ ràng trong trường hợp này sẽ là
    f = open(filename)
    # nothing in between!
    try:
        # do stuff with f
    finally:
        f.close()
    
    2 nhưng nếu bạn muốn xử lý các dòng trước khi lưu trữ chúng trong danh sách, tôi sẽ đề xuất một sự hiểu biết danh sách đơn giản.

Làm cách nào để đọc một dòng văn bản cụ thể trong Python?

Để đọc các dòng cụ thể từ tệp văn bản, vui lòng làm theo các bước sau:..
Mở tệp ở chế độ đọc.Để mở một tệp PASS PASS PIDE và MODE MODE R đến hàm Open ().....
Tạo một danh sách để lưu trữ số dòng.....
Tạo một danh sách để lưu trữ các dòng.....
Sử dụng cho vòng lặp với hàm Enumerate () để có được một dòng và số của nó.....
Đọc tệp theo số dòng ..

Làm thế nào để bạn đọc và viết các dòng trong Python?

Làm việc với các tệp bao gồm ba bước sau: Mở tệp.Thực hiện hoạt động đọc hoặc viết.Đóng tệp.... Đọc các tệp bằng đọc (), readline () và readlines ().

Dòng đọc trong Python là gì?

Phương thức readlines () tệp python Phương thức read () trả về một danh sách chứa từng dòng trong tệp dưới dạng mục danh sách.Sử dụng tham số gợi ý để giới hạn số lượng dòng được trả về.Nếu tổng số byte được trả về vượt quá số được chỉ định, không có thêm dòng nào được trả về.returns a list containing each line in the file as a list item. Use the hint parameter to limit the number of lines returned. If the total number of bytes returned exceeds the specified number, no more lines are returned.