Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách lấy số dòng file đang mở trong Python?


Python không hỗ trợ trực tiếp. Viết wrapper class. Ví dụ:

class FileLineWrapper(object):
    def __init__(self, file):
        self.f = file
        self.curr_line = 0
    def close(self):
        return self.f.close()
    def readline(self):
        self.curr_line += 1
        return self.f.readline()
    # cho phép dùng trong with
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

Dùng như sau:

f = FileLineWrapper(open("my_file", "r"))
f.readline()
print(f.line)

Kết quả: 1

Cách khác theo dõi số dòng nếu chỉ dùng readline:

f = open("my_file", "r")
for line_no, line in enumerate(f):
    print(line_no)
f.close()