파이썬에서 리스트 내용을 텍스트 파일로 저장
파이썬에서 리스트(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)
@jsup !blog
Blogger url: http://joviansummer.blogspot.com/2024/03/blog-post.html
Thank you, friend!


I'm @steem.history, who is steem witness.
Thank you for witnessvoting for me.
please click it!
(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.