파이썬에서 리스트 내용을 텍스트 파일로 저장

in hive-141029 •  11 months ago 

파이썬에서 리스트(list) 원소 하나가 텍스트 파일의 한줄이 되도록 저장하는 방법입니다.

x = ['abc', 'def', 'hij']

f = open('my_file.txt', 'w')
f.write('\n'.join(x))
f.close()

줄바꿈(\n)을 기준으로 join()을 통해서 리스트의 원소를 문자열로 변환해 주었습니다. 여기서 주의할 점은 처음부터 리스트의 원소가 모두 문자열(str)이어야 한다는 점입니다. 수자 등 다른 형식이 포함되어 있으면 오류가 발생합니다. 이런 경우에는 for 반복문을 이용해서 한줄씩 문자열로 변환해서 저장해 줄 수 있습니다.

x = ['abc', 'def', 'hij']

f = open('my_file.txt', 'w')
for item in x:
  f.writelines(str(item) + '\n')
f.close()

@joviansummer의 스팀 프로젝트

스팀 증인노드를 운영중입니다. @jswit에 증인투표해 주시면 감사하겠습니다.
(https://steemitwallet.com/~witnesses)

jswit 증인 노드 프로젝트를 시작합니다.

jsup 업보팅(upvoting) 서비스 소개

jsup 수혜자 지정 기능 추가

jsup 2.0 - 업보팅을 다시 위대하게

jSTEEM 프로젝트 - 텔레그램 챗봇으로 구현하는 스팀 블럭체인 탐색기

Steemit-Search - 스팀잇 포스팅 검색

STEEM.NFT - 디지털 아트 보존 프로젝트

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

@jsup !blog

Thank you, friend!
I'm @steem.history, who is steem witness.
Thank you for witnessvoting for me.
image.png
please click it!
image.png
(Go to https://steemit.com/~witnesses and type fbslo at the bottom of the page)

The weight is reduced because of the lack of Voting Power. If you vote for me as a witness, you can get my little vote.

Upvoted! Thank you for supporting witness @jswit.