Python 복습
Python으로 파일 다루기, 이메일 보내기
새롭게 알게된 것, 자주 헷갈리는 것 위주로 정리
from pathlib import Path
print(Path.home()) # 사용자 홈 디렉토리 확인
print(Path.cwd()) # 현재 작업 디렉토리 확인
# 폴더 내 파일 목록 확인
files = Path.cwd().glob('*')
for f in files:
print(f)
w : write. 이름이 동일한 파일이 있을 경우 이전 파일을 제거하고 새로 생성한다. 이를 방지하려면 x모드를 사용한다. f = open('파일명.txt', 'w')
f.write('작성할 내용')
f.close() # 파일 닫기
x : 같은 파일이 있는 경우 오류 발생. f = open('파일명.txt', 'x')
f.write('작성할 내용')
f.close() # 파일 닫기
r : read.f = open('파일명.txt', 'r')
print(f.read())
f.close() # 파일 닫기
a : append. 내용 추가f = open('파일명.txt', 'a')
f.write('작성할 내용')
f.close() # 파일 닫기
writelines() : 리스트 속의 요소들을 각각 하나의 행으로 하여 텍스트 파일에 기록할 수 있다. readlines() : 각각의 행을 리스트 요소로 변경할 수 있다. readline() : 행 하나씩 읽을 수 있다. encoding='CP949'를 추가한다. import openpyxl as xl
wb = xl.load_workbook('엑셀파일명.xlsx') # 엑셀 파일 불러오기
wb.sheetnames # 시트명 확인
sheet1 = wb['Sheet1'] # 작업할 시트 선택
# 셀 값 확인
# 1)
print(sheet1['A1'].value)
# 2)
print(sheet1.cell(row=1, column=1).value)
print(sheet1.cell(1,1).value)
# 가장 끝 번호 확인
print(sheet1.min_row, sheet1.max_row)
print(sheet1.min_column, sheet1.max_column)
wb.save('저장할 파일명.xlsx') 로 저장해주어야 결과가 반영되어 저장된다.sheet.insert_rows(행번호) / sheet.delete_rows(행번호)sheet.insert_cols(열번호) / sheet.delete_cols(열번호)구글의 smtp를 사용하여 이메일을 보낼 수 있다.
구글계정 2단계 인증 후, 지메일의 앱비밀번호를 별도로 설정해야 한다.
발송에 사용할 지메일을 IMAP을 사용으로 설정해야 한다.
import smtplib
from email.mime.text import MIMEText
# smtp 주소
s = smtplib.SMTP('smpt.gmail.com', 587)
# 기본적으로 포트 587로 설정되어있다.
# TLS 보안
s.starttls()
# 로그인
s.login('IMAP 사용 설정한 이메일 주소', '발급받은 앱 비밀번호')
# 메일 작성
msg = MIMEText('메일 내용')
msg['Subject'] = '메일 제목'
# 메일 보내기
s.sendmail('발신 메일', '수신 메일', msg.as_string())
# 로그아웃
s.quit()
from datetime import datetime, timedelta
datetime.today() # 오늘
datetime.today() + timedelta(1) # 내일
datetime.today().year/month/day
datetime.today().weekday() # 요일을 의미하는 weekday에만 뒤에 괄호가 붙음