파이썬(python)에서 파일을 읽는 한 가지 방법은 내장된 open() 명령을 사용한다.
results.txt 파일을 열기위해
result_f = open("c://results.txt") // c 드라이에 있는 result.txt 파일을 불러온다.
for each_line in result_f:
print(each_line)
// 파일 내 내용을 한 줄씩 출력
for each_line in result_f:
print(each_line)
// 파일 내 내용을 한 줄씩 출력
result_f.close() // 파일을 더 이상 사용하지 않으면 파일 핸들을 이용하여 파일을 닫는다.
◆ 최고점수 찾기
highest_score = 0
result_f = open("c://results.txt")
for each_line in result_f:
if float(line) > higthest_score:
hightest_score = float(line)
result_f.close()
print("The highest score was:")
print(highest_score)
print("The highest score was:")
print(highest_score)
오류가 발생한다. 오류가 왜 발생 할 까요 ?
results.txt 파일안에는 이름도 포함하고 있다. 이것이 프로그램에 문제를 일으킨것이다.
파일을 읽을 때 스트링 안에 숫자만 있는 것이 아니었기 때문이다.
※파일을 읽을 때에는 각 라인의 데이터를 분리하면 해결 할 수 있다.
★ split() 메소드 사용
파이썬(python) 스트링은 split()이라는 특별한 스트링 메소드를 제공한다.
highest_score = 0
result_f = open("c://results.txt")
for line in result_f:
(nane, score) = line.split() // split() 메소드를 호출하는 코드를 추가하여 name,score 변수를 만든다.
if float(score) > highest_score:
hightest_score = float(score)result_f.close()
print("The highest score was:")
print(highest_score)
출처 : http://ygang.tistory.com/19
'프로그래밍언어 > Python' 카테고리의 다른 글
파이썬 Dictionary (0) | 2012.08.02 |
---|---|
파이썬- 배열 & 메소드(데이터 정렬하기) 2 (0) | 2011.11.02 |
파이썬 -배열 안의 데이터(데이터 정렬하기) 1 (0) | 2011.11.02 |
파이썬 - 시간(time) 모듈 (0) | 2011.11.02 |
파이썬 - 함수.스코핑 룰 (0) | 2011.11.02 |