파일을 여는 함수
open()
파일모드 | 모드 이름 | 설명 |
"r" | 읽기 모드(read mode) | 파일의 처음부터 읽는다 |
"w" | 쓰기 모드(write mode) | 파일의 처음부터 쓴다. 파일이 없으면 생성된다. 만약 파일이 존재하면 기존의 내용은 지워진다. |
"a" | 추가 모드(append mode) | 파일의 끝에 쓴다. 파일이 없으면 생성된다. |
"r+' | 읽기와 쓰기 모드 | 파일에 읽고 쓸 수 있는 모드이다. 모드를 변경하려면 seek()가 호출된다. |
파일에 데이터 쓰기
outfile = open("d:\\phones1.txt", "w")
outfile.write("홍길동 010-1234-5678")
outfile.write("김철수 010-1234-5679")
outfile.write("김영희 010-1234-5680")
outfile.close()
파일에 데이터 추가하기
outfile = open("d:\\phones.txt", "a")
outfile.write("강감찬 010-1234-5681\n")
outfile.write("김유신 010-1234-5682\n")
outfile.write("정약용 010-1234-5683\n")
outfile.close()
파일에서 데이터 읽기
infile = open("d:\\proverbs.txt", "r")
for line in infile:
line = line.rstrip()
word_list = line.split()
for word in word_list:
print(word);
infile.close()
파일에서 전체 데이터 읽기
infile = open("d:\\phones.txt", "r")
lines = infile.read()
print(lines)