Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 현재 열린 파일 줄을 얻는 방법은 무엇입니까?


Python은 이를 직접 지원하지 않습니다. 래퍼 클래스를 작성할 수 있습니다. 예를 들어,

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()
    # to allow using in 'with' statements
    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.line)

이것은 출력을 줄 것입니다:1

readline 방법만 사용하는 경우 줄 번호를 추적하는 다른 방법이 있습니다. 예를 들어,

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