Hướng dẫn how do i see all the lines in a file in python? - làm cách nào để xem tất cả các dòng trong một tệp bằng 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 để xem nội dung của một tệp trong Python?

Python, đọc nội dung của một tập tin..
fileName = '/users/flavio/test.txt' file = open (fileName, 'r') #or file = open (fileName, mode = 'r').
Nội dung = Tệp. đọc().
dòng = tệp. ĐỌC LINE ().
tập tin. gần().

Làm cách nào để tìm ra có bao nhiêu dòng một tệp văn bản trong Python?

Sử dụng các đường đọc () để nhận số lượng dòng Đây là cách đơn giản nhất để đếm số lượng dòng trong một tệp văn bản trong Python.Phương thức Readlines () đọc tất cả các dòng từ một tệp và lưu trữ nó trong danh sách.Tiếp theo, sử dụng hàm Len () để tìm độ dài của danh sách không có gì ngoài tổng số dòng có trong một tệp. This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.

Làm cách nào để đọc 10 dòng từ một tệp trong Python?

Phương thức 1: FileObject.ReadLines () Một đối tượng tệp có thể được tạo trong python và sau đó readlines () phương thức có thể được gọi trên đối tượng này để đọc các dòng vào một luồng.fileobject.readlines() A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream.

Làm cách nào để viết một danh sách các dòng trong một tệp trong Python?

Các bước để viết danh sách vào một tệp trong Python..
Mở tệp ở chế độ ghi.Vượt qua đường dẫn tệp và chế độ truy cập W đến hàm Open ().....
Lặp lại danh sách bằng cách sử dụng một vòng lặp.Sử dụng cho vòng lặp để lặp từng mục từ một danh sách.....
Viết mục hiện tại vào tệp.....
Đóng tệp sau khi hoàn thành thao tác ghi ..