1. 파이썬 명령어
출력된 결과가 많거나, 결과물의 텍스트 파일이 필요할때, 출력 결과를 텍스트 파일로 저장할수도 있습니다.
import sys sys.stdout = open('output.txt','w') # 나머지 코드 작성
아래는 open문의 옵션입니다.
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (deprecated)
2. Command Line
명령 프롬프트상에서 실행하는 경우.
python test.py
python test.py > output.txt
python test.py >> output.txt
> 한개와 >> 두개의 차이는, 파일이 있을경우, 지우고 덮어쓸것인지(>), 파일의 끝에 이어붙일것인지(>>)의 차이입니다.
3. 경로지정하기
출력결과를 특정 폴더에 저장하고 싶을때,
명령프롬프트에서 실행하는 경우는, 출력파일이름 앞에 경로명을 추가해주면 됩니다.
python your_script.py > path/to/output_file/file_name.txt
파이선 스크립트에서도 파일명 앞에 경로명을 붙여주면 됩니다.
file = open('folder/output.txt','w')