반응형
SMALL
16. 파일 입출력
16.1 파일 생성하기
fileWrite = open("newFile.txt", 'w') # just 파일 생성
fileWrite.write("hello") # 쓰기
fileWrite.close() # 닫기
파일열기모드 | 설명 |
---|---|
r | 읽기 모드 |
w | 쓰기 모드 |
a | 추가 모드 - 파일의 마지막에 새로운 내용을 추가 시킬 때 사용 |
16.2 파일 읽기
readline()
- 파일의 첫번째 줄 읽기
f = open("C:/python/newFile.txt", 'r')
line = f.readline()
print(line)
f.close()
# 모든 줄 읽어서 출력하기
f = open("C:/python/newFile.txt", 'r')
while True:
line = f.readline()
if not line: break # line이 '' 이면
print(line)
f.close()
readlines()
- 모든 줄을 읽어서 각각의 줄을 요소로 갖는 리스트로 반환
f = open("C:/python/newFile.txt", 'r')
lines = f.readlines()
for line in lines:
print(line)
f.close()
>> ["--","--"]
read()
- 파일 내용 전체를 하나의 문자열로 반환
f = open("C:/python/newFile.txt", 'r')
data = f.read()
print(data)
f.close()
16.3 with
- with 블록을 벗어나는 순간 열린 파일 객체 f가 자동으로 close 됨
with open("newFile.txt", "w") as f:
f.write("hello")
반응형
LIST
'Python' 카테고리의 다른 글
[python] 모듈 (0) | 2020.09.06 |
---|---|
[python] 클래스 (0) | 2020.09.05 |
[python] 사용자 입력 (0) | 2020.09.05 |
[python] 함수 (0) | 2020.09.04 |
[python] for 문 (0) | 2020.09.03 |