파이썬에서 텍스트 파일을 한줄씩 읽어서 리스트(list)에 할당

by joviansummer
original STEEMIT post: https://steemit.com/blog/@joviansummer/list


파이썬에서 텍스트 파일을 읽어서 한줄씩 리스트(list)의 원소로 할당하는 방법입니다.

빈 리스트를 하나 선언한 후 for 반복문을 이용해서 간편하게 작업할 수 있습니다.

# my_data.txt 파일을 읽기('r')로 열기
f = open('my_data.txt', 'r')
f_data = []
# 파일 객체 f로부터 한줄씩 읽어서 리스트에 추가 
for line in f:
  f_data.append(line.rstrip())

파일을 열고 for 반복문을 이용해서 한줄씩 리스트에 append()로 할당합니다. 읽은 텍스트에는 줄바꿈이 포함되어 있으므로 제거하고 싶다면 rstip()을 이용해서 줄바꿈을 제거합니다.

Comments

Popular posts from this blog

GentBG will continue to burn STEEM, with reduced posting frequency

GentBG - why bother to burn STEEM?

jsup 2.1 - investor's relief (experiment on separation of investment and SNS)