본문 바로가기

Python_Beginer/Study

Python Open - writelines / readlines / readline

반응형

1. writelines()

Code 기본 사용법>

리스트변수 = ['리스트']

with open('파일명', 'w', encoding='인코딩 방식') as file:
file.writelines(리스트변수)


Code 예제>

list_str = ['Life is too short\n','You need Python\n']

with open('python.txt', 'w', encoding='utf-8') as file:
file.writelines(list_str)


Code 예제 출력물>


writelines는 리스트의 있는 문자열을 파일에 작성할때 사용 하는 명령어이다.

주의사항은 리스트 각 문자열 끝에 \n 개행 문자를 지정 해야된다.


2. readlines()

Code 기본 사용법>

with open('파일명', 'r', encoding='인코딩 방식') as file:
lines = file.readlines()
print(lines)


Code 예제>

with open('python.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
print(lines)


Code 예제 출력물>

['Life is too short\n', 'You need Python\n']


Process finished with exit code 0


readlines는 파일의 내용을 한 줄씩 리스트 형태로 변환하여 가져온다.
여기서 \n은 개행 문자를 의미한다. 실제로 파일을 열어보면 마지막 줄에 개행이 되어있으니 이것을 python에서 표현을 한다.

3. readline()
Code 기본 사용법>
with open('핑;ㄹ먕', 'r', encoding='인코딩 방식') as file:
line = None
while line != '':
line = file.readline()
print(line.strip('\n'))

Code 예제>

with open('python.txt', 'r', encoding='utf-8') as file:
line = None
while line != '':
line = file.readline()
print(line.strip('\n'))


Code 예제 출력물>

Life is too short

You need Python



Process finished with exit code 0


readline는 위에 readlines랑 다르게 한줄씩 순차적으로 읽을때 사용한다.

그러므로 while 반복문을 활용해서 사용한다.

출력때 \n을 안해주면 빈줄이 계속 출력되므로 strip으로 개행 문자를 삭제 처리해서 출력한다.

반응형

'Python_Beginer > Study' 카테고리의 다른 글

Python String(문자열)  (0) 2019.04.28
Python Pickling / Unpickling  (0) 2019.04.26
Python Open - With as  (0) 2019.04.25
Python Open - w / r / a  (0) 2019.04.25
Pycharm 한글 에러 발생 해결 방안  (0) 2019.04.24