[파이썬] 출력 결과를 텍스트 파일로 저장하기(sys모듈, open함수)

InAnarchy·2023년 4월 14일
0

Python

목록 보기
10/14
post-thumbnail

출력 결과 저장하기

  • 출력된 결과가 많아서 결과물의 텍스트 파일로 확인할 때
  • 출력 결과를 텍스트 파일로 저장할 때

sys

  • sys 모듈을 사용하여 표준 출력을 파일로 리다이렉션
import sys 
path = 'hellofile.txt'
sys.stdout = open(path, 'w')
print('Hello, World')

전체 결과 출력

import sys

sys.stdout = open('경로/파일명.txt', 'w')

image = cv2.imread("경로/opencv.png", cv2.IMREAD_GRAYSCALE)
if image is None: 
    raise Exception("error")

np.set_printoptions(threshold=np.inf, linewidth=np.inf)
image1 = np.zeros(image.shape[:2], image.dtype)
for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        pixel = image[i,j]
        print(pixel, end = " ")
sys.stdout.close()

특정 결과 출력

  • print() 함수에 file 인자를 지정하여 특정 결과만 출력할 수도 있다.
import sys

sys.stdout = open('경로/파일명.txt', 'w')

f = cv2.imread("경로/opencv.png", cv2.IMREAD_GRAYSCALE)
if image is None: 
    raise Exception("error")

np.set_printoptions(threshold=np.inf, linewidth=np.inf)
image1 = np.zeros(image.shape[:2], image.dtype)
for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        pixel = image[i,j]
        if pixel == 76:
            print(pixel, end = " ", file = f)
sys.stdout.close()

open()

  • 파일을 생성할때에 사용하는 함수
  • 첫 번째 인자는 파일 이름이고, 두 번째 인자는 파일 모드
  • 읽기(기본값) r, 쓰기 w, 이어쓰기 a모드 등
  • 모든 작업이 끝난 뒤에는 close() 함수를 사용하여 파일을 닫아주어야함
  • 개방한 파일을 자동으로 닫아주는 with문을 사용하면 번거로움이 감소

형태

with open(파일명, 파일모드문자열) as 파일객체:
    수행할 명령문

예시를 보자.

output = "result"

with open("output.txt", "w", encoding="utf-8") as file:
    file.write(output) 
    #write() 함수를 사용해 output 변수에 저장된 값을 파일에 씀 
with open("pixel_76.txt", "w", encoding="utf-8") as file:## 결과를 저장할 텍스트 파일 오픈
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            pixel = image[i, j]
            if pixel == 76:
                file.write(f"Pixel value: {pixel}, at position: ({i}, {j})\n") #저장 

참고

넘파이 배열을 텍스트파일로 변환하는 방법도 있다.

numpy.savetxt

np.set_printoptions(threshold=np.inf, linewidth=np.inf)
coordinates = []

image1 = np.zeros(image.shape[:2], image.dtype)

for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        pixel = image[i, j]
        if pixel == 76:
            coordinates.append([i, j])

coordinates_array = np.array(coordinates)
np.savetxt("coordinates.txt", coordinates_array, fmt='%d', delimiter=",")

배열을 생략없이 전체 출력하기 위해

np.set_printoptions(threshold=np.inf, linewidth=np.inf)

를 사용했다.

픽셀이 76인 경우에만 빈 배열 coordinates에 추가했고,
저장명은 coordinates.txt
좌표는 정수형태,
구분자로 콤마 , 를 설정했다.

굿!

profile
No sibal Keep going.

0개의 댓글