# [python] mysql 백업파일에서 특정 테이블 부분만 별도로 저장하기

- 주소: https://duotone.co.kr/entry/python-mysql-%EB%B0%B1%EC%97%85%ED%8C%8C%EC%9D%BC%EC%97%90%EC%84%9C-%ED%8A%B9%EC%A0%95-%ED%85%8C%EC%9D%B4%EB%B8%94-%EB%B6%80%EB%B6%84%EB%A7%8C-%EB%B3%84%EB%8F%84%EB%A1%9C-%EC%A0%80%EC%9E%A5%ED%95%98%EA%B8%B0
- 글쓴이: 서기㏇
- 카테고리: 개발·프로그래밍
- 작성일: 2024-09-10
- 태그: dump, MySQL, Python, save, specify, table, 별도, 저장, 테이블, 특정

```
import re
import argparse

def extract_table_data(input_file, output_file, table_name):
    with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8') as outfile:
        in_table = False
        table_content = []

        for line in infile:
            if line.strip().startswith(f"DROP TABLE IF EXISTS `{table_name}`"):
                in_table = True

            if in_table:
                table_content.append(line)

            if line.strip() == "UNLOCK TABLES;" and in_table:
                in_table = False
                outfile.writelines(table_content)
                table_content = []

def main():
    parser = argparse.ArgumentParser(description="Extract specific table data from MySQL backup SQL file.")
    parser.add_argument("input_file", help="Input SQL backup file path")
    parser.add_argument("output_file", help="Output file path for extracted data")
    parser.add_argument("table_name", help="Name of the table to extract")

    args = parser.parse_args()

    extract_table_data(args.input_file, args.output_file, args.table_name)
    print(f"Extraction complete. Data for table '{args.table_name}' has been saved to '{args.output_file}'.")

if __name__ == "__main__":
    main()
```

대용량 풀백업받은 sql파일에서 특정 테이블 관련 부분만 별도의 파일로 저장하는 파이썬 소스입니다.
