Old Branch

Python Basic - 파이썬 파일처리하기(1) Read, Write

woolbro 2019. 7. 1. 23:29
반응형

이번 포스팅은 파이썬 파일 처리입니다!

 

파일을 다루는 방법을 정리 해보려고 하는데요, csv 형태의 파일을 읽어오고 쓰는 것을 작성 해 보려고 합니다.

 

어플리케이션을 개발 할 때에 빠질수 없는 데이터 쓰기와 읽기에 대해 같이 공부해 보도록 하겠습니다!

 


파일을 처리하기 위한 과정

파이썬에서 파일을 처리하기 위한 과정은, 우리가 책에 내용을 작성하거나 읽는 과정과 같습니다.

 

 

파일을 읽기 위해서 우선, 파일을 "열고" 파일을 "읽고" 파일을 "닫습니다".

 

파이썬에서는 위와 같은 과정을 쉽게 할 수 있도록 open, write, close 등을 제공합니다.

 

자세히 알아보도록 하겠습니다~!!!

 

 

 

파일 읽기 (open, with)

파일을 읽는 과정입니다.

 

우선, 아래와 같은 내용을 읽어보도록 하겠습니다.

아래의 내용을 review.txt 라고 하겠습니다.

The film, projected in the form of animation, imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues, which eventually paves the path for gaining a fresh perspective on an age-old problem. The story also happens to centre around two parallel characters, Shundi King and Hundi King, who are twins, but they constantly fight over unresolved issues planted in their minds by external forces from within their very own units.

 

파일을 열때에는 open이라는 함수와 경로를 씁니다.

 

이 open이라는 함수는, 괄호 안에 있는 내용을 읽어 오겠다. 라는 내용입니다.

 

resource 는 파일의 경로를 얘기 해 줍니다. resource 폴더 안에 있는 review.txt라는 파일을 열어서 'r'하겠다는 뜻입니다. 여기서 r은, "읽기" 입니다.

 

파일을 읽어 왔으니, 출력 해 보겠습니다. 제대로 읽어왔는지 확인 해야 하니까요!

 

위의 코드는, open으로 읽어온 review.txt를 file에 저장 한 것입니다. 파이썬은 친절하게, print문 안에 file이라는 변수를 넣어주면 해당하는 파일을 출력 해 줍니다.

print(file)

위와같이 실행 해 주면 

 

 

이렇게, file안에 담겨진 내용을 출력 해 줍니다.

 

이때 가장 중요한 것은, 읽고 난 후의 동작입니다!! 파일을 열었으니 읽고 출력 해 보았습니다. 여기서 가장 중요한 동작은 다 읽은 후에 파일을 "닫아주는 동작" 입니다.

 

변수이름 . close() -> file.close()

 

으로 파일을 닫아줍니다. 

 

open으로 읽는 방법 외에 다른 방법으로 읽는 방법이 있습니다!

바로 with open() ~ 이라는 방법입니다.

 

with open 구문이 일반 open과 다른점은, close() 함수의 유무입니다!

 

위에있었던 open() 이라는 함수는 파일을 여는 동작과 닫는 동작을 모두 신경 써 주어야 했지만,

 

with open 구문은, 구문이 끝남과 동시에 close()문을 자동적으로 사용 해 주는 구문입니다

 

파일을 읽는 데에는 위의 두가지를 응용한 방법들을 사용합니다! 아래의 코드를 참고해주세요 :)

 

파일을 읽는데에 사용되는 방법 들

아래의 내용을 작성하기 위해 resource 폴더를 만들고 하위에 review.txt와 score.txt를 넣었습니다. 내용은 다음과 같습니다.

review.txt V

...더보기

The film, projected in the form of animation,
imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues,
which eventually paves the path for gaining a fresh perspective on an age-old problem.
The story also happens to centre around two parallel characters, Shundi King and Hundi King,
who are twins, but they constantly fight over unresolved issues planted in their minds
by external forces from within their very own units.

 

score.txt V

...더보기

95
78
92
89
100
66

예제 코드입니다.

# 파일 읽기
# 예제 1
file = open('resource/review.txt','r') #파일을 열 때에는, open이라는 함수.
content = file.read()
print(content)
file.close()

# 파일 읽기
# 예제 2
print("-----file open use <with>------------------------------------")
with open('resource/review.txt','r') as file_tmp:
    c = file_tmp.read()
    print(c)
    print(list(c)) ##c를 list화


# 파일 읽기
# 예제 3
print("---------file open use <with> line")
with open('resource/review.txt','r') as file_tmp:
    for c in file_tmp:
        print(c) ##라인단위로 출력

    for s in file_tmp:
        print(s.strip())


# 파일 읽기
# 예제 4
print("-----------file open")
with open('resource/review.txt','r') as file_tmp:
    content = file_tmp.read()
    print(">",content)
    content = file_tmp.read() ### 이 이후에는 파일의 커서가 맨 뒤로 가있기 때문에 
    print(">",content)        ### 읽지 못함(내용이 없음)
    

# 파일 읽기
# 예제 5
print("-----------file open")
with open('resource/review.txt','r') as file_tmp:
    line = file_tmp.readline()
    #print(line) #한줄만 읽어서 가져오기 때문에 반복문이 필요
    while line:
        print(line, end = ' ')
        line = file_tmp.readline()
    

# 파일 읽기
# 예제 6
print("-----------file open")
with open('resource/review.txt','r') as file_tmp:
    content = file_tmp.readlines() ##readlines는 줄바꿈의 형태까지 리스트로.
    print(content) ## 줄바꿈의 형태까지 리스트로 가질 수 있음
    for c in content:
        print(c , end=' **** ') ## \n을 **** 으로 출력

# 파일 읽기
# 예제 7
print("")
print("")
print("-----------file example")
with open('resource/score.txt','r') as file_tmp:
    score = []
    for line in file_tmp:
        score.append(int(line)) ## 텍트스파일 안에 있는 내용은 문자열로 인식
    print(score) #읽은 파일을 리스트로 넣음

print("Average : {:6.3}".format(sum(score)/len(score)))