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

Python에서 파일 위치 찾기

<시간/>

tell() 메소드는 파일 내의 현재 위치를 알려줍니다. 즉, 다음 읽기 또는 쓰기는 파일의 시작 부분부터 그 만큼의 바이트에서 발생합니다.

Seek(offset[, from]) 메서드는 현재 파일 위치를 변경합니다. offset 인수는 이동할 바이트 수를 나타냅니다. from 인수는 바이트가 이동할 참조 위치를 지정합니다.

from이 0으로 설정되면 파일의 시작을 참조 위치로 사용하고 1은 현재 위치를 참조 위치로 사용하고 2로 설정하면 파일 끝을 참조 위치로 사용합니다. .

예시

위에서 만든 foo.txt 파일을 가져오겠습니다.

#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str
# Check current position
position = fo.tell()
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10)
print "Again read String is : ", str
# Close opend file
fo.close()

이것은 다음 결과를 생성합니다 -

Read String is : Python is
Current file position : 10
Again read String is : Python is