티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Writing a list to a file with Python, with newlines
줄 바꿈과 함께 Python으로 파일에 리스트 쓰기
문제 내용
How do I write a list to a file? writelines()
doesn't insert newline characters, so I need to do:
리스트를 파일에 쓰려면 어떻게 해야 합니까? writelines()은 줄 바꿈 문자를 삽입하지 않으므로 다음 작업을 수행해야 합니다.
f.writelines([f"{line}\n" for line in lines])
높은 점수를 받은 Solution
Use a loop:
루프 사용:
with open('your_file.txt', 'w') as f:
for line in lines:
f.write(f"{line}\n")
For Python <3.6:
Python <3.6의 경우:
with open('your_file.txt', 'w') as f:
for line in lines:
f.write("%s\n" % line)
For Python 2, one may also use:
파이썬 2의 경우 다음을 사용할 수도 있다.
with open('your_file.txt', 'w') as f:
for line in lines:
print >> f, line
If you're keen on a single function call, at least remove the square brackets []
, so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.
단일 함수 호출에 관심이 있다면 적어도 대괄호 []를 제거하여 인쇄할 문자열이 한 번에 하나씩 만들어지도록 합니다(listcomp가 아닌 genexp). 전체 문자열 리스트를 구체화하기 위해 메모리를 낭비 할 필요는 없습니다.
가장 최근 달린 Solution
Simply:
간단히:
with open("text.txt", 'w') as file:
file.write('\n'.join(yourList))
출처 : https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python-with-newlines
'개발 > 파이썬' 카테고리의 다른 글
Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session' 에러 수정하기 (0) | 2022.12.06 |
---|---|
딕셔너리 복사 후 사본만 편집하기 (0) | 2022.12.06 |
비어 있지 않은 폴더 삭제하기 (0) | 2022.12.06 |
파이썬에서 파일 크기 확인하기 (0) | 2022.12.05 |
Python에서 argparse로 양의 정수만 허용하기 (0) | 2022.12.05 |