본문 바로가기

SeSAC 금융데이터 분석가/RPA

9/16 금

728x90

1. 파일 자동화

os, shutil

import os             # 운영체제와 관련된 라이브러리

os.listdir('경로')     # 하위 폴더, 파일 확인
os.path.exists('경로') # 폴더 또는 파일 경로 존재여부 확인
os.path.isdir('경로')  # 경로 존재여부 확인
os.makedirs('경로')    # 경로에 폴더 생성
os.remove()           # 파일 삭제
os.unlink()           # 파일 삭제

import shutil                                   # 파일, 폴더와 관련된 라이브러리

shutil.copyfile('원본 파일 경로', '사본 파일 경로') # 파일 복사
shutil.copytree()                               # 폴더 복사
shutil.rmtree()                                 # 폴더 삭제

CSV

open mode: w(쓰기, 파일 없으면 생성), r(읽기, 파일 없으면 Error), r+(읽기 또는 쓰기, 파일 없으면 Error),
a(파일 끝에 추가로 쓰기, 파일 없으면 생성), a+(읽기 또는 추가, 파일 없으면 생성)

with open('orders.csv', 'w') as f:
    f.write('고객명, 상품명, 수량, 금액\n')
    f.write('홍길동, 폴드4, 1, 800000\n')

with open('orders.csv', 'a') as f:
    f.write('제이슨, 버즈프로, 1, 200000\n')
    
with open('orders.csv', 'r') as f:
    a = f.read()
print(a)
"""
고객명, 상품명, 수량, 금액
홍길동, 폴드4, 1, 800000
제이슨, 버즈프로, 1, 200000
"""

with open('orders.csv', 'r') as f:
    data = f.readline()
data.rstrip().split(',')
# ['고객명', ' 상품명', ' 수량', ' 금액']

with open('orders.csv', 'r') as f:
    data = f.readlines()
print(data)
# ['고객명, 상품명, 수량, 금액\n', '홍길동, 폴드4, 1, 800000\n', '제이슨, 버즈프로, 1, 200000\n']

 

2. 엑셀 자동화

python -m pip install openpyxl # 엑셀 파일 다루는 패키지

import openpyxl

new_excel = openpyxl.Workbook()      # 새 엑셀 만들기
read_excel = openpyxl.load_workbook(file_path, read_only=True) # 엑셀 불러오기 (읽기 모드)
target_sheet = read_excel.active     # 활성화된 시트 가져오기
new_excel.create_sheet('newsheet')   # 시트 생성
target_sheet = new_excel['newsheet'] # 활성화된 시트 가져오기


new_excel = openpyxl.Workbook()                 # 새 엑셀 만들기
active_sheet = new_excel.active                 # 셀 가져오기
cell = active_sheet[‘A1’] # 특정 셀 가져오기(sheet['A']는 열, sheet['1']는 행, sheet['1:2']는 여러 행)
print(cell.value)                               # 셀 값 가져오기
new_excel.append([value1, value2, value3, ...]) # 새 데이터 입력하기
new_excel.save(‘target_path’)                   # 엑셀 파일 저장하기

for row in study_sheet.iter_rows():
    for cell in row:
        print(cell)
        print(cell.value)
        
"""
<Cell 'study_sheet'.A1>
1
<Cell 'study_sheet'.B1>
2
<Cell 'study_sheet'.A2>
3
<Cell 'study_sheet'.B2>
4
<Cell 'study_sheet'.A3>
5
<Cell 'study_sheet'.B3>
6
<Cell 'study_sheet'.A4>
7
<Cell 'study_sheet'.B4>
8
<Cell 'study_sheet'.A5>
9
<Cell 'study_sheet'.B5>
10
<Cell 'study_sheet'.A6>
11
<Cell 'study_sheet'.B6>
12
"""

 

3. 이메일 다루기

SMTP: 메일 발송을 위해 메일 서비스 제공 회사와 사용자 간에 약속된 규약 (Simple Mail Transfer Protocol)

IMAP : 전자 메일에 액세스 (Internet Messaging Access Protocol)

파이썬 이메일 관리 라이브러리: email, smtplib

첨부파일 타입: application/octet-stream, application/pdf, application/msword, vnd.ms.excel, zip

# 1. SMTP 메일 발송하기
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

msg = MIMEMultipart('alternative') # 편지 봉투

if attachment:                     # 첨부파일이 있을 경우의 편지 봉투
msg = MIMEMultipart('mixed')

msg['From'] = SMTP_USER
msg['To'] = target_addr   # type: str
msg['Subject'] = subject  # 편지 제목
text = MIMEText(contents) # 편지 내용
msg.attach(text)                   # 편지지

# 2. 첨부파일 추가하기
from email.mime.base import MIMEBase
from email import encoders
from os.path import basename

email_file = MIMEBase('application', 'octet-stream') # 이진 파일 첨부 시
with open('file_path', 'rb') as f:
	file_data = f.read()
    
email_file.set_payload(file_data)
encoders.encode_base64(email_file) # 첨부한 이진 파일(워드, 엑셀 등) 인코딩 -> 텍스트로 전달. 나중에 다시 이진 파일로 디코딩

file_name = basename('file_path')
email_file.add_header('Content-Disposition',
'attachment', file-name=file_name)

msg.attach(email_file)

# 3. 메시지 발송하기
import smtplib

smtp = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT)
smtp.login(SMTP_USER, SMTP_PASSWORD)
smtp.sendmail('from_addr', 'to_addr', msg.as_string())
smtp.close()

# 4. 참조 추가하기
msg['CC'] = 'cc_targets'
targets = ','.join([target_addrs, cc_targets, hidden_cc])

smtp.sendmail(SMTP_USER, targets.split(','), msg.as_string()) # targets type: list

 

4. 텔레그램 연동

문자나 사진, 문서 등을 암호화하여 전송할 수 있는 메신저

pip install python-telegram-bot # 라이브러리 설치

import telegram

token = "token"
bot = telegram.Bot(token)
updates = bot.getUpdates()
print(updates[-1])
"""
{'message': {'caption_entities': [], 'text': 'SB', 'new_chat_members': [], 'new_chat_photo': [], 'entities': [], 'photo': [], 'supergroup_chat_created': False, 'date': 1663422323, 'channel_chat_created': False, 'message_id': 129, 'group_chat_created': False, 'chat': {'first_name': 'Jiyeon', 'last_name': 'Lee', 'id': 5496582700, 'username': 'Jeon222', 'type': 'private'}, 'delete_chat_photo': False, 'from': {'last_name': 'Lee', 'first_name': 'Jiyeon', 'username': 'Jeon222', 'is_bot': False, 'language_code': 'ko', 'id': 5496582700}}, 'update_id': 313764386}
"""
print(updates[-1].message.chat.id)    # 신규 메시지가 들어온 채팅방 id 조회
print(updates[-1].message.text)       # 신규 메시지 조회

bot.send_message(chat_id, msg)        # 메시지 보내기

image_file = open('image_path', 'rb') # 이미지 보내기
bot.send_photo(chat_id, image_file)

audio_file = open('audio_path', 'rb') # 오디오 보내기
bot.send_audio(chat_id, audio_file)

video_file = open('video_path', 'rb') # 비디오 보내기
bot.send_video(chat_id, video_file)

 

 

728x90