Python

Python: txt 파일을 csv 파일로 변환

dewstream 2025. 7. 12. 08:00
728x90

※ Python: Convert a txt file to a CSV file.
 
안녕하세요. 듀스트림입니다.
 
요즘 파이썬도 조금씩 공부 중입니다.
 
txt 파일로 받은 파라미터 값들을 csv 파일로 변환이 필요해서 만들었습니다.


import csv
from pathlib import Path
from typing import List, Dict

def parse_data(file_path: str) -> List[Dict[str, str]]:
    """
    Parse data from the input file, skipping headers and footers.
    
    Args:
        file_path (str): Path to the input text file.
        
    Returns:
        List[Dict[str, str]]: List of dictionaries containing parsed data.
        
    Raises:
        FileNotFoundError: If the input file does not exist.
        UnicodeDecodeError: If the file cannot be decoded as UTF-8.
    """
    data = []
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
            for line in lines[2:-1]:  # Skip header and footer
                if line.strip():
                    parts = [part.strip() for part in line.split('|')]
                    if len(parts) == 3:
                        data.append({
                            'name': parts[0],
                            'setting': parts[1],
                            'description': parts[2]
                        })
        return data
    except FileNotFoundError:
        print(f"Error: Input file '{file_path}' not found.")
        raise
    except UnicodeDecodeError:
        print(f"Error: Unable to decode '{file_path}' as UTF-8.")
        raise

def save_as_markdown(data: List[Dict[str, str]], output_file: str) -> None:
    """
    Save parsed data as a Markdown table.
    
    Args:
        data (List[Dict[str, str]]): List of dictionaries containing parsed data.
        output_file (str): Path to the output Markdown file.
        
    Raises:
        PermissionError: If there's no write permission for the output file.
    """
    try:
        with open(output_file, 'w', encoding='utf-8') as file:
            file.write("| No | name | setting | description |\n")
            file.write("|----|------|---------|-------------|\n")
            for i, row in enumerate(data, 1):
                file.write(f"| {i} | {row['name']} | {row['setting']} | {row['description']} |\n")
    except PermissionError:
        print(f"Error: No permission to write to '{output_file}'.")
        raise

def save_as_csv(data: List[Dict[str, str]], output_file: str) -> None:
    """
    Save parsed data as a CSV file.
    
    Args:
        data (List[Dict[str, str]]): List of dictionaries containing parsed data.
        output_file (str): Path to the output CSV file.
        
    Raises:
        PermissionError: If there's no write permission for the output file.
    """
    try:
        with open(output_file, 'w', encoding='utf-8', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(['No', 'name', 'setting', 'description'])
            for i, row in enumerate(data, 1):
                writer.writerow([i, row['name'], row['setting'], row['description']])
    except PermissionError:
        print(f"Error: No permission to write to '{output_file}'.")
        raise

def main() -> None:
    """
    Main function to parse data and save as Markdown and CSV files.
    """
    input_file = "show_all_output.txt"
    output_md_file = "output_table.md"
    output_csv_file = "output_table.csv"

    try:
        data = parse_data(input_file)
        save_as_markdown(data, output_md_file)
        save_as_csv(data, output_csv_file)
        print(f"Markdown file saved to '{output_md_file}'.")
        print(f"CSV file saved to '{output_csv_file}'.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")

if __name__ == "__main__":
    main()

▸ 원본 txt 파일: show_all_output.txt

 
▸ 실행

 
▸ 결과 csv 파일: output_table.csv

 
이렇게 나옵니다.
 
재밌네요.


오늘은 여기까지~
 

728x90