파일입출력 기본 - 파이썬

Posted by HULIA(휴리아)
2019. 4. 28. 19:59 백엔드개발/파이썬

파이썬 파일 입출력

open()과 close()는 파이썬 내장함수라서 모듈 import없이 사용가능

open(filename, mode);
close();

파일 처리 모드

r : 읽기모드(모드를 쓰지 않으면 기본모드)
w : 쓰기모드
a : 파일에 맨뒤에 추가모드
rb : 이진 파일 읽기모드
wb : 이진 파일 쓰기모드
ab : 이진 파일 맨뒤에 추가모드
w+ : 읽기쓰기모드

현재 디렉토리 위치 출력(os모듈)

import os
print os.getcwd();

파일 쓰기 예시

s = """hello
hi
korea."""
f = open('t.txt', 'w')
f.write(s)
f.close()

파일 읽기 예씨

f = open('t.txt', 'r') #open('t.txt') 같은 의미다
s = f.read()
print s
f.close()

라인 단위로 파일 읽기

총 4가지 방식이 있음
1)for문을 이용하는 방법

f = open('t.txt')
i = 1
for line in f:
    print i, ":", line,
    i +=1
f.close()

2)readline() : 한번에 한줄씩 읽는다

f = open('t.txt')
line = f.readline()
i = 1
while line:
    print i, ":", line,
    line = f.readline()
    i +=1
f.close()

3)readlines() : 파일 전체를 라인 단위로 끊어서(개행문자까지 한번씩 읽어드림) 리스트에 저장한다

f = open('t.txt')
print f.readlines()

f.seek(0) #파일 맨 앞으로 이동
i = 1
for line in f.readlines():
    print i, ":", line,
    i +=1
f.close()

4)xreadlines() : readlines()와 유사하지만 파일 전체를 한꺼번에 읽지 않고, 상황별로 필요한 라인만 읽는다. 대용량의 파일을 for문 등으로 라인 단위로 읽을 때 효율적이다

f = open('t.txt')
print f.xreadlines()

f.seek(0) #파일 맨 앞으로 이동
i = 1
for line in f.xreadlines():
    print i, ":", line,
    i +=1
f.close()

1), 4)방법을 추천함

라인 단위로 파일 쓰기

lines = ['first line\n','second line\n','third line\n']
f = open('t1.txt','w')
f.writelines(lines)
f.close

# 파일 내용 확인
f = open('t1.txt')
print f.read()
f.close()
lines = ['first line','second line','third line']
f = open('t1.txt','w')
f.write('\n'.join(lines))
f.close

# 파일 내용 확인
f = open('t1.txt')
print f.read()
f.close()

파일내에 존재하는 단어의 수

f = open('t.txt')
s = f.read()
n = len(s.split()) # split() -> 공백문자를 기준으로 문자를 잘라 list 화
print n
f.close()

기존 파일에 내용 추가 예시

f = open('t.txt', 'a')
f.write('forth line\n')
f.close()

# 파일내용 확인
f = open('t.txt')
print f.read()
f.close()

파일 내 임의 위치로 접근

seek(n) : 파일의 첫번째 위치에서 n번째 바이트로 포인터 이동
tell() : 파일 내 현재 포인터 위치를 반환

f = open('t.txt', 'w+')
s='02121222022'
f.write(s)


# 파일내용 확인
f.seek(5)       # 시작부터 5바이트 이동
print f.tell()  # 현재위치 알려줌
print f.read(1) # 1문자 읽기

f.close()