Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีหา Current Line Number ของไฟล์ที่เปิดอยู่ใน Python

Python ไร้ built-in สำหรับนี้ ต้องเขียน wrapper class เอง:

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()
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

ใช้งาน:

f = FileLineWrapper(open("my_file", "r"))
f.readline()
print(f.curr_line)  # 1

วิธีง่ายกว่า ใช้ enumerate:

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