티스토리 뷰
파일객체 = 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 프로그래밍
'Python' 카테고리의 다른 글
Python,module re [정규표현식] (0) | 2016.04.29 |
---|---|
Python, 예외처리 (0) | 2016.04.29 |
Python,module glob (0) | 2016.04.29 |
Python,module os.path [파일의 경로명] (0) | 2016.04.21 |
Python, str 내장모듈 (0) | 2016.04.21 |
- Total
- Today
- Yesterday
- 상수
- highlightbackground
- highlightthickness
- borderwidth
- tkinter command & bind [명령어묶기와 사건묶기] Python
- activebackground
- indicatoron
- ManyToOne
- activeforeground
- 폼
- checkbutton
- Excel
- Java
- IdClass
- Composite Key
- 리눅스
- Module
- JPA
- Private
- tkinter
- command
- onetomany
- fetch join
- disabledforeground
- apache
- vba
- Python
- 파이썬
- Linux
- FetchType
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |