StoryCode

csv 를 읽어 mysql create table 문장 생성

Python
반응형

# Ubuntu 에서 특정 디렉토리에 있는 CSV 들을 읽어서 각 csv 에 매칭되는 create table sql 생성한다. 

 

import csv
import os
import getpass

# 특정 디렉토리 경로
username = getpass.getuser()
directory = os.path.join("/home", username, "mycsvdirectory/")

# 디렉토리 내의 모든 csv 파일 목록 가져오기
filenames = os.listdir(directory)
csv_files = [f for f in filenames if f.endswith(".csv")]

with open("CREATETABLE.sql", "w") as f:
    f.truncate()

# 각 csv 파일을 읽어 CREATE TABLE 문 생성 및 저장
for csv_file in csv_files:
    print("Filename :" + csv_file)
    with open(os.path.join(directory, csv_file), "r") as f:
        reader = csv.reader(f)

        # 첫 번째 행 (헤더)을 읽어 컬럼 목록으로 변환
        headers = next(reader)

        # 컬럼명에서 '-'를 '_'로 변경
        headers = [col.replace("-", "_") for col in headers]
        print(headers)

        # 첫 번째 컬럼을 제외한 나머지 컬럼 목록 생성
        remaining_headers = headers[0:]
        print(remaining_headers)

        # 각 컬럼의 최대 길이 저장
        column_max_lengths = {}
        for col in remaining_headers:
            column_max_lengths[col] = 0

        # 데이터 읽어서 각 컬럼 최대 길이 계산
        for row in reader:
            for i, col in enumerate(row):
                # print(row)
                if len(col) > column_max_lengths[remaining_headers[i]]:
                    column_max_lengths[remaining_headers[i]] = len(col)
        print(column_max_lengths);

        # DROP TABLE IF EXISTS 문 생성
        drop_table_sql = f"DROP TABLE IF EXISTS MYTABLE_{csv_file[:-4].upper()}_TBL;\n"

        # CREATE TABLE 문 생성
        create_table_sql = f"""
            CREATE TABLE IF NOT EXISTS MYTABLE_{csv_file[:-4].upper()}_TBL (
                {", ".join([f"{col} VARCHAR({column_max_lengths[col]})" for col in remaining_headers])}
            );

            CREATE INDEX idx_{csv_file[:-4].upper()}_TBL ON MYTABLE_{csv_file[:-4].upper()}_TBL ({headers[0]});
        """

        # SQL 문을 1.0.result.CREATETABLE.sql 파일에 저장
        with open("CREATETABLE.sql", "a") as f:
            f.write(drop_table_sql)
            f.write(create_table_sql + "\n")

반응형

'Python' 카테고리의 다른 글

..., :, Ellipsis  (0) 2023.09.21
Debugging.디버깅.breakpoint()  (0) 2023.09.20
print().5 Ways  (0) 2022.12.18
print.format.text.lpad.rpad  (0) 2022.12.18
Ubuntu.pip3 설치  (0) 2022.09.27

..., :, Ellipsis

Python
반응형

참조,설명 Good : https://www.youtube.com/watch?v=3IhPcPCncAU

반응형

'Python' 카테고리의 다른 글

csv 를 읽어 mysql create table 문장 생성  (0) 2024.03.16
Debugging.디버깅.breakpoint()  (0) 2023.09.20
print().5 Ways  (0) 2022.12.18
print.format.text.lpad.rpad  (0) 2022.12.18
Ubuntu.pip3 설치  (0) 2022.09.27

Debugging.디버깅.breakpoint()

Python
반응형

# 참조 : https://www.youtube.com/watch?v=WD63ykLOGzs

 

1) 코드(Ex> test.py)에 디버깅할 위치에 breakpoint() 추가

 

2) python test.py 실행

breakpoint() 를 만나며 python debugger 인 (Pdb) 가 뜸.

 

3) (pdb) 명령어

명렁 설명  
소스보기 l
변수보기 변수명 <Enter>, print (변수)
다음 한 줄 실행 n
계속 실행 c
breakpoint 추가 무조건 정지하는 break 줄번호.
- breakpoint 를 만나면 "무조건" break 한다.
- breakpoint 만 등록되며, c 를 실행해야 코드가 실행된다.
- 등록할 때 몇 번째 Breakpoint 인지 "Breakpoint Condition Number" 를 알려준다.
이 번호는 아래 Condition 명령에서 사용된다.
Ex> Breakpoint 1 at test.py # 여기서 1 이 Breakpoint Condition Number 이다.
breakpoint 에 조건 걸기 condition "Breakpoint Condition Number" 조건코드
- 무조건 정지하는 breakpoint 를 특정 조건에서만 정지되도록 변경
- Ex> condition 1 result=="lucky" # 1번 Breakpoint Condition Number 인 무조건 정지하는 breakpoint 를 result == lucky 일때만 정지하는 break 로 변경
- 주로 딥러닝 학습 loss 터질때 사용

4) 주된 사용법

- breakpoint() 가 많으면 소스가 지저분해지고 배포시 일일이 삭제해야 한다.

- 그러니 코드 첫 줄에만 breakpoint() 를 넣고, breakpoint 명령으로 break 위치를 설정하고 c 로 넘어가는 게 편하다.

 

 

반응형

'Python' 카테고리의 다른 글

csv 를 읽어 mysql create table 문장 생성  (0) 2024.03.16
..., :, Ellipsis  (0) 2023.09.21
print().5 Ways  (0) 2022.12.18
print.format.text.lpad.rpad  (0) 2022.12.18
Ubuntu.pip3 설치  (0) 2022.09.27

print().5 Ways

Python
반응형
No Way  
1 print(name + ' : ' + str(age))
2 print(name, ':', age)
3 print(f'{name} : {age}')
4 print('%s : %s' % (name, age))
5 print('{} : {}'.format(name, age))

 

 

반응형

'Python' 카테고리의 다른 글

..., :, Ellipsis  (0) 2023.09.21
Debugging.디버깅.breakpoint()  (0) 2023.09.20
print.format.text.lpad.rpad  (0) 2022.12.18
Ubuntu.pip3 설치  (0) 2022.09.27
python 버전 관리  (0) 2021.12.17

print.format.text.lpad.rpad

Python
반응형

print(f'{text}')

print(f'{text:#<20}') # rpad

print(f'{text:>20}') # lpad

print(f'{text:.^20}') # lrpad ( center text )

 

반응형

'Python' 카테고리의 다른 글

Debugging.디버깅.breakpoint()  (0) 2023.09.20
print().5 Ways  (0) 2022.12.18
Ubuntu.pip3 설치  (0) 2022.09.27
python 버전 관리  (0) 2021.12.17
유튜브 업로드  (0) 2021.04.06

Ubuntu.pip3 설치

Python
반응형

1) sudo curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

2) sudo python3 get-pip.py

3) pip3 # /usr/local/bin/ 에 있음

반응형

'Python' 카테고리의 다른 글

print().5 Ways  (0) 2022.12.18
print.format.text.lpad.rpad  (0) 2022.12.18
python 버전 관리  (0) 2021.12.17
유튜브 업로드  (0) 2021.04.06
기차표 예매 (SRT)  (0) 2021.04.06

python 버전 관리

Python
반응형

1. which python

 

2. rm /usr/bin/python

 

3. ln -s /usr/bin/python3.8 /usr/bin/python

 

4. python -V

 

반응형

'Python' 카테고리의 다른 글

print.format.text.lpad.rpad  (0) 2022.12.18
Ubuntu.pip3 설치  (0) 2022.09.27
유튜브 업로드  (0) 2021.04.06
기차표 예매 (SRT)  (0) 2021.04.06
python.gmail.로그인.메일발송  (0) 2020.06.15

유튜브 업로드

Python
반응형

kminito.tistory.com/5

 

[Python] Google API를 이용하여 유튜브에 동영상 올리기

개요 이전 게시물에서 파이썬으로 만든 동영상을 Google API를 이용하여 유튜브에 올리고자 합니다. 필요한 기능은 단순히 유튜브에 동영상을 올리는 것 뿐이므로, 가이드에서 제공하는 예제를 이

kminito.tistory.com

 

 

반응형

'Python' 카테고리의 다른 글

Ubuntu.pip3 설치  (0) 2022.09.27
python 버전 관리  (0) 2021.12.17
기차표 예매 (SRT)  (0) 2021.04.06
python.gmail.로그인.메일발송  (0) 2020.06.15
Python.설치파일만들기  (0) 2020.04.06

기차표 예매 (SRT)

Python
반응형

kminito.tistory.com/25?category=373099

 

[Python] 파이썬으로 SRT 매진 표 예매하기 (+셀레늄)

 파이썬으로 SRT 표 예매 과정을 자동화 한 것입니다. 웹에서의 동작은 셀레늄을 이용했습니다. 아래 내용을 보시면 아시겠지만 단순히 사람이 하는 반복 작업을 파이썬을 통해 자동화 한 것이

kminito.tistory.com

 

 

반응형

'Python' 카테고리의 다른 글

python 버전 관리  (0) 2021.12.17
유튜브 업로드  (0) 2021.04.06
python.gmail.로그인.메일발송  (0) 2020.06.15
Python.설치파일만들기  (0) 2020.04.06
(작성중) Python.QT5.mathplotlib.막대그래프  (0) 2020.04.02

python.gmail.로그인.메일발송

Python
반응형

참조) https://oceancoding.blogspot.com/2019/11/smtp.html

 

선행작업)

1) 구글 계정 설정 ( Gmail 설정 아님 )

아래에서 "앱 비밀번호" 를 클릭하고 들어가, 비밀번호를 생성하면 된다.

 

 

 

2) 메일 발송 코드

import smtplib
from email.mime.text import MIMEText
 
# 세션 생성
s = smtplib.SMTP('smtp.gmail.com', 587)
 
# TLS 보안 시작
s.starttls()
 
# 로그인 인증
s.login('xxx@gmail.com', '16자리앱비밀번호')
 
# 보낼 메시지 설정
msg = MIMEText('내용 : 한글 내용')
msg['Subject'] = '제목 : 오션 코딩 학원'
 
# 메일 보내기
s.sendmail('sender@gmail.com', 'recevier@gmail.com', msg.as_string())
 
# 세션 종료
s.quit()

 

 

반응형

'Python' 카테고리의 다른 글

유튜브 업로드  (0) 2021.04.06
기차표 예매 (SRT)  (0) 2021.04.06
Python.설치파일만들기  (0) 2020.04.06
(작성중) Python.QT5.mathplotlib.막대그래프  (0) 2020.04.02
Application.PyQT5.Anaconda.PyCharm  (0) 2020.04.02