파이썬 print 함수를 파일로 리디렉션하는 방법

PythonBeginner
지금 연습하기

소개

Python 의 print 함수는 콘솔에 정보를 표시하는 데 유용한 도구입니다. 하지만 이 출력을 파일에 저장하고 싶은 경우가 있습니다. 이러한 기능은 로깅 (logging), 보고서 생성 또는 나중 분석을 위해 프로그램 결과를 저장하는 데 특히 유용합니다.

이 랩에서는 Python 의 print 함수의 출력을 파일로 리디렉션하는 방법을 배우게 됩니다. 기본적인 print 연산부터 시작하여 해당 출력을 다양한 모드로 파일에 리디렉션하는 방법, 마지막으로 이 기술의 몇 가지 실용적인 응용 프로그램을 살펴보겠습니다.

Python print() 함수의 기본 이해

출력을 파일로 리디렉션하기 전에 먼저 Python 에서 print() 함수가 어떻게 작동하는지 이해해 보겠습니다. print() 함수는 Python 에서 출력을 표시하는 데 가장 일반적으로 사용되는 함수 중 하나입니다.

print() 함수의 기본 구문은 다음과 같습니다.

print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

여기서:

  • value1, value2, ...: 인쇄할 값
  • sep: 값 사이의 구분 기호 (기본값은 공백)
  • end: 마지막 값 뒤에 추가되는 문자열 (기본값은 줄 바꿈)
  • file: 출력이 가는 파일 객체 (기본값은 콘솔)
  • flush: 스트림을 강제로 플러시할지 여부 (기본값은 False)

print() 함수의 기본 사용법을 보여주는 간단한 Python 스크립트를 만들어 보겠습니다.

  1. WebIDE 를 열고 "File" 메뉴를 클릭하고 "New File"을 선택하여 새 파일을 만듭니다.
  2. 파일을 /home/labex/project 디렉토리에 print_basics.py로 저장합니다.
  3. 파일에 다음 코드를 추가합니다.
## Basic print examples
print("Hello, Python!")
print("Multiple", "values", "with", "spaces")
print("Values", "with", "dashes", sep="-")
print("No newline at the end", end=" ")
print("This continues on the same line")

## Printing different data types
print("Integer:", 42)
print("Float:", 3.14)
print("Boolean:", True)

## Printing variables
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
  1. Ctrl+S 를 누르거나 "File" > "Save"를 클릭하여 파일을 저장합니다.
  2. 터미널을 열고 다음을 입력하여 스크립트를 실행합니다.
python3 print_basics.py

다음과 유사한 출력이 표시되어야 합니다.

Hello, Python!
Multiple values with spaces
Values-with-dashes
No newline at the end This continues on the same line
Integer: 42
Float: 3.14
Boolean: True
Name: Alice Age: 30

이 예제는 다양한 값 인쇄, 구분 기호 사용자 정의 및 줄 끝 제어를 포함하여 print() 함수의 기본 기능을 보여줍니다.

print()로 출력 형식 지정

f-string (형식화된 문자열 리터럴) 또는 format() 메서드를 사용하여 print() 함수의 출력을 형식화할 수도 있습니다.

print_basics.py 파일에 형식화된 print 예제를 몇 개 더 추가해 보겠습니다.

  1. print_basics.py 파일을 다시 엽니다.
  2. 파일 끝에 다음 코드를 추가합니다.
## Using f-strings (Python 3.6+)
name = "Bob"
age = 25
print(f"Name: {name}, Age: {age}")

## Using format() method
print("Name: {}, Age: {}".format(name, age))

## Formatting numbers
price = 19.99
quantity = 5
total = price * quantity
print(f"Price: ${price:.2f}, Quantity: {quantity}, Total: ${total:.2f}")
  1. 파일을 저장하고 다시 실행합니다.
python3 print_basics.py

새로운 출력에는 다음이 포함되어야 합니다.

Name: Bob, Age: 25
Name: Bob, Age: 25
Price: $19.99, Quantity: 5, Total: $99.95

이제 print() 함수의 기본 사항을 이해했으므로 출력을 파일로 리디렉션하는 방법을 알아보겠습니다.

이제 print() 함수가 어떻게 작동하는지 이해했으므로 콘솔에 표시하는 대신 출력을 파일로 리디렉션하는 방법을 살펴보겠습니다. 핵심은 print() 함수의 file 매개변수를 사용하는 것입니다.

파일에 출력 쓰기

print() 함수의 출력을 파일로 리디렉션하려면 다음을 수행해야 합니다.

  1. 쓰기 모드로 파일을 엽니다.
  2. file 매개변수를 사용하여 파일 객체를 print() 함수에 전달합니다.
  3. 완료되면 파일을 닫습니다.

이를 보여주는 새로운 Python 스크립트를 만들어 보겠습니다.

  1. /home/labex/project 디렉토리에 print_to_file.py라는 새 파일을 만듭니다.
  2. 파일에 다음 코드를 추가합니다.
## Open a file in write mode
output_file = open("output.txt", "w")

## Redirect print output to the file
print("This is line 1 of our output file.", file=output_file)
print("This is line 2 of our output file.", file=output_file)
print("This is line 3 with numbers:", 42, 3.14, file=output_file)

## Close the file
output_file.close()

print("Output has been written to output.txt")
  1. 파일을 저장하고 실행합니다.
python3 print_to_file.py
  1. 콘솔에 "Output has been written to output.txt" 메시지가 표시되어야 합니다.
  2. output.txt 파일의 내용을 확인해 보겠습니다.
cat output.txt

다음과 같은 내용이 표시되어야 합니다.

This is line 1 of our output file.
This is line 2 of our output file.
This is line 3 with numbers: 42 3.14

with 문 사용 (권장 접근 방식)

Python 에서 파일을 처리하는 더 나은 방법은 with 문을 사용하는 것입니다. with 문은 예외가 발생하더라도 자동으로 파일을 닫습니다. 예제를 수정해 보겠습니다.

  1. /home/labex/project 디렉토리에 print_to_file_with.py라는 새 파일을 만듭니다.
  2. 파일에 다음 코드를 추가합니다.
## Using the 'with' statement to handle file operations
with open("output_with.txt", "w") as output_file:
    print("This line is written using the 'with' statement.", file=output_file)
    print("The file will be automatically closed after this block.", file=output_file)
    print("Numbers and other data types:", 100, 3.14159, True, file=output_file)

print("Output has been written to output_with.txt")
  1. 파일을 저장하고 실행합니다.
python3 print_to_file_with.py
  1. 새 파일의 내용을 확인합니다.
cat output_with.txt

다음과 같은 내용이 표시되어야 합니다.

This line is written using the 'with' statement.
The file will be automatically closed after this block.
Numbers and other data types: 100 3.14159 True

with 문은 Python 에서 파일을 처리하는 데 권장되는 접근 방식입니다. 그 이유는 다음과 같습니다.

  • 블록이 끝나면 자동으로 파일을 닫습니다.
  • 예외를 적절하게 처리합니다.
  • 코드를 더 깔끔하고 읽기 쉽게 만듭니다.

이제 전통적인 파일 처리와 더 현대적인 with 문 방식을 모두 사용하여 print() 함수의 출력을 파일로 리디렉션하는 방법을 알게 되었습니다.

기존 파일에 출력 추가하기

이전 단계에서는 파일을 열 때 "w" 모드를 사용했는데, 이는 새 파일을 만들거나 기존 파일을 덮어씁니다. 그러나 때로는 현재 내용을 지우지 않고 기존 파일의 끝에 새 내용을 추가하고 싶을 수 있습니다. 이러한 목적으로 "a" (추가) 모드를 사용합니다.

파일에 추가하기

출력을 기존 파일에 추가하는 방법을 보여주는 스크립트를 만들어 보겠습니다.

  1. /home/labex/project 디렉토리에 append_to_file.py라는 새 파일을 만듭니다.
  2. 파일에 다음 코드를 추가합니다.
## First, create a file with some initial content
with open("append_example.txt", "w") as file:
    print("This is the initial content of the file.", file=file)
    print("Created on: 2023-09-01", file=file)

print("Initial content has been written to append_example.txt")

## Now, append to the file
with open("append_example.txt", "a") as file:
    print("\nThis content is being appended to the file.", file=file)
    print("Appended on: 2023-09-02", file=file)

print("Additional content has been appended to append_example.txt")

## Let's check the final content
print("\nFinal content of the file:")
with open("append_example.txt", "r") as file:
    print(file.read())
  1. 파일을 저장하고 실행합니다.
python3 append_to_file.py

다음과 유사한 출력이 표시되어야 합니다.

Initial content has been written to append_example.txt
Additional content has been appended to append_example.txt

Final content of the file:
This is the initial content of the file.
Created on: 2023-09-01

This content is being appended to the file.
Appended on: 2023-09-02

간단한 로그 파일 만들기

파일에 추가하는 일반적인 사용 사례는 기존 항목을 제거하지 않고 새 항목을 추가하는 로그 파일을 만드는 것입니다. 간단한 로깅 예제를 만들어 보겠습니다.

  1. /home/labex/project 디렉토리에 simple_log.py라는 새 파일을 만듭니다.
  2. 파일에 다음 코드를 추가합니다.
import datetime

def log_message(message):
    """Append a timestamped message to the log file."""
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open("application.log", "a") as log_file:
        print(f"[{timestamp}] {message}", file=log_file)

## Simulate some application events
log_message("Application started")
log_message("Processing data...")

## Simulate some user activity
user = "Alice"
log_message(f"User '{user}' logged in")

## Simulate an error
try:
    result = 10 / 0
except Exception as e:
    log_message(f"Error occurred: {e}")

log_message("Application shutting down")

print("Log entries have been written to application.log")
print("\nContents of the log file:")
with open("application.log", "r") as log_file:
    print(log_file.read())
  1. 파일을 저장하고 실행합니다.
python3 simple_log.py

다음과 유사한 출력이 표시되어야 합니다.

Log entries have been written to application.log

Contents of the log file:
[2023-09-10 15:30:45] Application started
[2023-09-10 15:30:45] Processing data...
[2023-09-10 15:30:45] User 'Alice' logged in
[2023-09-10 15:30:45] Error occurred: division by zero
[2023-09-10 15:30:45] Application shutting down

실제 타임스탬프는 현재 날짜와 시간을 반영합니다.

이 간단한 로깅 예제는 파일에 출력을 추가하는 실용적인 응용 프로그램을 보여줍니다. 스크립트가 실행될 때마다 이전 항목을 제거하지 않고 새 로그 항목을 파일에 추가합니다. 이는 응용 프로그램 실행 기록을 추적하는 데 유용합니다.

print() 함수와 함께 추가 모드를 사용하면 로깅, 데이터 수집 및 기록 보관과 같은 많은 실제 응용 프로그램에 필수적인 파일에 새 내용을 지속적으로 추가할 수 있습니다.

실용적인 응용 프로그램 만들기 - 보고서 생성기

이 마지막 단계에서는 print() 함수를 파일 리디렉션과 함께 사용하여 서식 있는 보고서를 생성하는 방법을 보여주는 더 실용적인 응용 프로그램을 만들 것입니다. 이 예제는 이 기술을 실제 시나리오에 적용하는 방법을 보여줍니다.

판매 보고서 생성기 구축

일부 샘플 데이터를 기반으로 판매 보고서를 생성하는 스크립트를 만들어 보겠습니다.

  1. /home/labex/project 디렉토리에 sales_report_generator.py라는 새 파일을 만듭니다.
  2. 파일에 다음 코드를 추가합니다.
import datetime

## Sample sales data (product, quantity, price)
sales_data = [
    {"product": "Laptop", "quantity": 5, "price": 899.99},
    {"product": "Mouse", "quantity": 10, "price": 24.99},
    {"product": "Keyboard", "quantity": 7, "price": 49.99},
    {"product": "Monitor", "quantity": 3, "price": 149.99},
    {"product": "Headphones", "quantity": 12, "price": 79.99}
]

def generate_sales_report(filename):
    """Generate a formatted sales report and save it to a file."""
    today = datetime.datetime.now().strftime("%Y-%m-%d")

    with open(filename, "w") as report_file:
        ## Print the report header
        print("=" * 60, file=report_file)
        print(f"SALES REPORT - Generated on {today}", file=report_file)
        print("=" * 60, file=report_file)
        print("", file=report_file)

        ## Print the table header
        print(f"{'Product':<15} {'Quantity':<10} {'Price ($)':<10} {'Total ($)':<10}", file=report_file)
        print("-" * 50, file=report_file)

        ## Print sales data and calculate totals
        grand_total = 0
        total_items = 0

        for item in sales_data:
            product = item["product"]
            quantity = item["quantity"]
            price = item["price"]
            total = quantity * price

            print(f"{product:<15} {quantity:<10} {price:<10.2f} {total:<10.2f}", file=report_file)

            grand_total += total
            total_items += quantity

        ## Print the summary
        print("-" * 50, file=report_file)
        print(f"{'Total':<15} {total_items:<10} {'':<10} {grand_total:<10.2f}", file=report_file)
        print("", file=report_file)
        print("=" * 60, file=report_file)
        print("End of Report", file=report_file)

## Generate the report
report_filename = "sales_report.txt"
generate_sales_report(report_filename)

print(f"Sales report has been generated: {report_filename}")
print("\nContents of the sales report:")
with open(report_filename, "r") as file:
    print(file.read())
  1. 파일을 저장하고 실행합니다.
python3 sales_report_generator.py

다음과 같은 출력이 포함된 출력이 표시되어야 합니다.

Sales report has been generated: sales_report.txt

Contents of the sales report:
============================================================
SALES REPORT - Generated on 2023-09-10
============================================================

Product         Quantity   Price ($)  Total ($)
--------------------------------------------------
Laptop          5          899.99     4499.95
Mouse           10         24.99      249.90
Keyboard        7          49.99      349.93
Monitor         3          149.99     449.97
Headphones      12         79.99      959.88
--------------------------------------------------
Total           37                     6509.63

============================================================
End of Report

이 예제는 파일 리디렉션과 함께 print() 함수를 사용하여 잘 서식된 보고서를 만드는 방법을 보여줍니다. 보고서에는 머리글, 표 형식 레이아웃의 서식 있는 데이터 및 요약 정보가 포함됩니다.

동적 로그 회전 시스템 만들기

스크립트가 실행될 때마다 새 로그 파일을 만드는 로그 회전 시스템을 보여주는 예제를 하나 더 만들어 보겠습니다.

  1. /home/labex/project 디렉토리에 rotating_log.py라는 새 파일을 만듭니다.
  2. 파일에 다음 코드를 추가합니다.
import datetime
import os

def create_log_file():
    """Create a new log file with a timestamp in the filename."""
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    log_dir = "logs"

    ## Create logs directory if it doesn't exist
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    return os.path.join(log_dir, f"log_{timestamp}.txt")

def log_event(log_file, event_type, message):
    """Log an event to the specified log file."""
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open(log_file, "a") as f:
        print(f"[{timestamp}] [{event_type.upper()}] {message}", file=f)

## Create a new log file
log_filename = create_log_file()
print(f"Created new log file: {log_filename}")

## Simulate some application events
log_event(log_filename, "info", "Application started")
log_event(log_filename, "info", "Initializing modules...")
log_event(log_filename, "warning", "Configuration file not found, using defaults")
log_event(log_filename, "info", "Processing data batch #1")
log_event(log_filename, "error", "Failed to connect to database server")
log_event(log_filename, "info", "Retrying connection in 5 seconds")
log_event(log_filename, "info", "Connection established")
log_event(log_filename, "info", "Application shutting down")

print("\nLog file contents:")
with open(log_filename, "r") as f:
    print(f.read())
  1. 파일을 저장하고 실행합니다.
python3 rotating_log.py

다음과 유사한 출력이 표시되어야 합니다.

Created new log file: logs/log_20230910_153045.txt

Log file contents:
[2023-09-10 15:30:45] [INFO] Application started
[2023-09-10 15:30:45] [INFO] Initializing modules...
[2023-09-10 15:30:45] [WARNING] Configuration file not found, using defaults
[2023-09-10 15:30:45] [INFO] Processing data batch #1
[2023-09-10 15:30:45] [ERROR] Failed to connect to database server
[2023-09-10 15:30:45] [INFO] Retrying connection in 5 seconds
[2023-09-10 15:30:45] [INFO] Connection established
[2023-09-10 15:30:45] [INFO] Application shutting down

이 예제는 Python 에서 파일 출력의 보다 고급 응용 프로그램을 보여줍니다. 스크립트가 실행될 때마다 이름에 타임스탬프가 있는 새 로그 파일을 생성하여 로그 구성 및 관리에 도움이 됩니다.

이러한 실용적인 예제는 print() 함수의 출력을 파일로 리디렉션하여 보고서 생성기 및 로깅 시스템과 같은 유용한 응용 프로그램을 만드는 데 사용할 수 있는 방법을 보여줍니다. 이 랩에서 배운 기술은 나중에 참조하거나 분석하기 위해 프로그램 출력을 저장해야 하는 많은 실제 시나리오에 적용할 수 있습니다.

요약

이 랩에서는 Python print() 함수의 출력을 콘솔 대신 파일로 리디렉션하는 방법을 배웠습니다. 다음은 다룬 주요 개념입니다.

  1. print() 함수의 기본 사항, 매개변수 및 형식 옵션 포함
  2. file 매개변수를 사용하여 print() 출력을 파일로 리디렉션하는 방법
  3. 파일 작업 시 쓰기 모드 ("w") 와 추가 모드 ("a") 의 차이점
  4. 보다 안전한 파일 처리를 위한 with 문 사용
  5. 파일 출력 리디렉션의 실용적인 응용 프로그램, 다음 포함:
    • 로그 파일 생성
    • 서식 있는 보고서 생성
    • 로그 회전 시스템 구현

이러한 기술은 다음과 같은 많은 실제 시나리오에 유용합니다.

  • 응용 프로그램 이벤트 및 오류 로깅
  • 데이터 보고서 생성
  • 나중 분석을 위해 프로그램 출력 저장
  • 서식 있는 텍스트 파일 생성

print() 함수 출력의 파일로의 리디렉션을 마스터함으로써, 더 다재다능하고 실용적인 응용 프로그램을 만드는 데 도움이 되는 강력한 Python 프로그래밍 도구를 얻었습니다.