python에서 파일 읽고 쓰기 예제
python에서 파일을 읽고 쓰는 간단한 예제다.
파일 open & close
open(filename, mode)
지원하는 mode는 다음과 같다.
- 'r' : 읽기 모드
- 'w' : 쓰기 모드
- 'x' : 파일 독점 모드로 생성, 만약 같은 이름의 파일이 있으면 'FileExistsError'에러 발생
- 'a' : 쓰기 모드, 파일 존재 시 새로운 쓰기는 파일 맨 끝에 추가
- 'b' : 바이너리 모드
- 't' : 텍스트 모드
- '+' : 업데이트 모드 (읽기/쓰기)
파일이 없을 때 'FileNotFoundError' exception이 발생한다. 파일 열기를 성공하면, file object를 반환한다.
파일 open은 다음과 같이 사용할 수 있다.
try:
f = open('hello.txt','r')
f.close()
except FileNotFoundError:
print('FileNotFound')
open에서 반환되는 file object를 사용하고 마지막 파일을 닫을 때 close()를 사용하여 파일을 닫는다.
with 구문을 사용하여 파일을 open할수 있으며, with 구문을 사용할 경우 별도의 close를 수행할 필요는 없다.
with open('hello.txt','r') as f:
print(f.read())
파일 쓰기
파일에 데이터를 쓰기위해서는 file object의 write(string)를 사용하면 된다.
write(string)
파일 open시 텍스트 모드로 설정한 경우는 문자열을 입력 파라메터로 사용하고, 바이너리 모드로 설정한 경우 byte-like object를 입력으로 사용한다. 리턴 값으로 쓰여진 길이를 반환한다.
텍스트 모드의 쓰기 예
f = open('hello.txt','w')
len = f.write('hello\npython\n')
f.write('writen len %d\n'%(len))
value = ('my number is', 9)
f.write(str(value))
f.flush()
f.close()
바이너리 모드의 쓰기 예
f = open('hello.dat','wb')
len = f.write(bytearray(b'\x01\x02\x03\x04\x05\x06'))
f.flush()
f.close()
파일 읽기
파일에서 데이터를 읽기 위해서 file object의 read(size) , readline()을 사용한다.
read(size)
readline()
read는 입력된 길이에 해당하는 데이터를 읽어오며, size입력이 없을 경우 전체 파일을 읽어온다. readline은 파일에서 한 줄씩('\n') 데이터를 읽어온다.
위 2의 예제 코드에서 쓰여진 파일을 읽을 때 다음과 같이 할 수 있다.
with open('hello.txt','r') as f:
print(f.read())
with open('hello.dat','rb') as f:
print(f.read())
실행 결과는 다음과 같다.
hello
python
writen len 13
('my number is', 9)
b'\x01\x02\x03\x04\x05\x06'
readline을 사용해 한 줄씩 읽을 경우는 아래와 같이 할 수 있다.
with open('hello.txt','r') as f:
print(f.readline())
실형 결과는 다음과 같다.
hello
또한, for 구문을 사용해 file object에서 한 줄씩 읽어 올 수 있다.
with open('hello.txt','r') as f:
for line in f:
print(line)
실행 결과
hello
python
writen len 13
('my number is', 9)
액세스 위치 받아오기
현재 액세스 중인 파일의 위치를 알고자 할 경우 file object의 tell()을 사용하면 된다.
tell()
현재의 파일 위치를 정수로 반환한다.
액세스 위치 변경
파일의 액세스 위치를 바꾸기 위해 seek을 사용한다.
seek(offset, whence)
파라미터
- whence
- 0: 파일의 맨 처음 위치
- 1: 파일의 현재 위치
- 2: 파일의 마지막 위치
- offset - whence를 기준으로 한 위치 offset. 텍스트 모드인 경우 0보다 큰 값이어야 한다. 0 보다 작을 경우 UnsupportedOperation exception이 발생한다.
텍스트 모드인 경우 예제
with open('hello.txt','r') as f:
print(f.readline())
f.seek(1, 0)
print(f.readline())
실행 결과
hello
ello
바이너리 모드인 경우의 예제
with open('hello.dat','rb') as f:
print(f.read())
f.seek(1, 0)
print(f.tell())#파일 위치
print(f.read(1))
f.seek(-2, 2)
print(f.tell())
print(f.read())
실행 결과
b'\x01\x02\x03\x04\x05\x06'
1
b'\x02'
4
b'\x05\x06'
댓글
댓글 쓰기