Python, 파일 입출력
파일객체 = open(file,mode)
file : 파일명
mode : 파일을 열때의 모드를 의미하여, 다음의 문자열의 조합으로 사용가능
r : 읽기 (Default)
w : 쓰기
a : 쓰기 + 이어쓰기
+ : 읽기 + 쓰기
b : 바이너리
t : 텍스트 (Default)
텍스트모드인 경우 유닉스에서는 newline이 '\n'으로 적용되며, 윈도우에서는 '\r\n'으로 적용됨
파일로부터 읽고 쓰기 위해서는 read()함수와 문자열을 쓰는 write()함수가 제공됨
파일을 열고 할일을 모두 완료했을경우 close()함수로 파일을 닫아줘야함
>>> f = open('test.txt','w') #test.txt.파일을 쓰기모두 열었음 >>> f.write('Python') #test.txt파일에 "Python"이라는 문자열을 기록함 6 #기록된 문자의 갯수 >>> f.close() #파일 닫기 >>> f = open('test.txt') #파일을 읽기모드로 열었음 >>> f.read() #파일내용 읽기 'Python' >>> f.close() #파일 닫기 >>> f.closed #파일 닫혀있는지 확인하기 True |
-. file.write()
파일의 문자열을 기록
-. file.read()
파일내용을 모두 읽어들인후 포인터를 마지막으로 이동
>>> file.read() 'start\nPython1\nPython2\nPython3\nPython4\nPython5\nPython6\nend' >>> file.read() '' |
-. file.readline()
readline()함수를 호출할때마다 한줄씩 읽은 문자열을 반환함
>>> file = open('test.txt') >>> file.readline() 'start\n' >>> file.readline() 'Python1\n' >>> file.readline() 'Python2\n' >>> file.readline() 'Python3\n' |
-. file.readlines()
readlines()함수는 파일의 모든 내용을 줄단위로 잘라서 리스트로 반환함
>>> file = open('test.txt') >>> file.readlines() ['start\n', 'Python1\n', 'Python2\n', 'Python3\n', 'Python4\n', 'Python5\n', 'Python6\n', 'end'] |
-. file.tell()
현재 파일의 어디까지 읽고 썻는지 위치를 반환
>>> file = open('test.txt') >>> file.tell() 0 >>> file.readline() 'start\n' >>> file.tell() 7 >>> file.readline() 'Python1\n' >>> file.tell() 16 |
-. file.seek()
파일에 대한 포인터를 원하는 위치로 이동시켜줌
>>> file = open('test.txt') >>> file.read() 'start\nPython1\nPython2\nPython3\nPython4\nPython5\nPython6\nend' >>> file.tell() 64 >>> file.seek(0) 0 >>> file.tell() 0 >>> file.readlines() ['start\n', 'Python1\n', 'Python2\n', 'Python3\n', 'Python4\n', 'Python5\n', 'Python6\n', 'end'] >>> file.close() |
with문을 이용하여 file.close()를 사용하지 않아도 파일이 닫히므로 파일을 실수로 닫지 않아 발생하는 오류에 대해서 어느정도 대처가 가능함
>>> with open('test.txt') as file: print(file.readline())
start
>>> file.closed True |
참조 : 빠르게 활용하는 파이썬3 프로그래밍