본문 바로가기
STUDY

Python / 파이썬 coding시 기억해둘만한 것들

by PsychoFLOOD 2021. 10. 6.
728x90

최근에 Python으로 소소하게 업무에 필요한 tool을 만들면서 기억해둘법한 것들을 정리해야 겠다는 생각이 들었다.

물론 그때그때 검색해서 찾아도 되지만 쉽게 찾기가 어려웠다거나 나름 삽질을 했던 것들을 앞으로 여기에 하나씩 추가하면서 적어둘 예정...

1. etree로 xml 순회시 특정 태그의 특정 attrib에 해당하는 값을 찾은 후 그 태그의 자식태그를 순회하면서 값을 찾거나 해야 할때.

using etree to search specific tag and its child traversal.

import xml.etree.ElementTree as ET
tree = ET.parse(file_path)
tree_root = tree.getroot()
for tag in tree_root.iter("특정tag")
	if tag.attrib["특정attrib"] == 블라블라:
    	for child in tag:
        	#child.tag값이나 child.attrib["특정attrib"]으로 찾은 태그의 자식태그들로 순회하면서 검색
            #자식태그? 들중 변경이 필요한 경우 child.attrib["특정attrib"] = 변경값으로 변경가능
	#아래 명령으로 위에서 변경한 특정 attrib들이 적용된 파일로 저장가능
    tree.write(file_path)

 

2. 모든 표준출력/표준에러를 파일로 내보내고 싶을때
문제는 이렇게 해두면 수행중 shell창에는 아무것도 나오지 않는다..

every standard output/error output to file io

log_file = 적당한 파일경로와 이름할당
log = open(log_file, "wt")
sys.stdout = log
sys.stderr = log

 

3. print문을 아예 막아버리고 싶을때

to block print statement

import sys
sys.stdout = open(os.devnull, 'w')
#막은 걸 풀고 싶을때는 아래 명령 사용
sys.stdout = sys.__stdout__

 

4. pyinstaller로 배포시 최초수행경로 판단(.exe로 실행한 경로와 .py를 수행한 경로 판단)

detect initial execute path when release by pyinstaller or .py

if getattr(sys, 'frozen', False):
#pyinstaller를 통해 만들어진 .exe 로 수행한 경우 최초경로. .exe가 압축이 풀리면서 사용자 appdata 폴더의 임시폴더에 생성되므로 기억해야 함.
    execute_path = os.path.dirname(os.path.abspath(sys.executable))  
else:
    execute_path = os.path.dirname(os.path.abspath(__file__))  #.py 로 실행한 경우의 경로

 

5. pyinstaller로 수행시 .py 수행경로에 위치한 리소스(이미지 등)를 못찾을때

to resolve unable locate resource file by release pyinstaller

#pyinstaller 로 수행시 경로가 sys._MEIPASS인듯..
try:
    os.chdir(sys._MEIPASS)
    print(sys._MEIPASS)
except:
    os.chdir(os.getcwd())

 

6. 특정확장자 파일목록을 뽑아서 작업해야 할 경우

get specific file extension files

path="./"
file_list = os.listdir(path)
file_list_xml = [file for file in file_list if file.endswith(".xml")]
print("XML_File_List"+','.join(file_list_xml))

for file in file_list_xml:
	#블라블라~

 

7. 오늘날짜_현재시각 스트링이 필요한 경우

get today date and time string

from datetime import datetime
datetime.today().strftime("%Y%m%d") +"_" + datetime.today().strftime("%H%M%S")

 

8. Paramiko를 이용한 sftp file download
get명령으로 download 파일 경로지정시 파일이름까지 지정해야 제대로 저장됨

get sftp file download by paramiko package

import paramiko

sftpURL = "" #IP
sftpUser = "" #id
sftpPass = "" #password

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(sftpURL, username=sftpUser, password=sftpPass)

ftp = ssh.open_sftp()
remote_path = ""
local_path = ""  #local_path에는 filename까지 포함하여 명시해야 함
ftp.get(remote_path, local_path)

ftp.close()
ssh.close()

 

9. full path에서 경로명/파일이름/확장자만 필요할때

get path/filename/extension from full path

from pathlib import Path
import os

full_path = ""
name = Path(full_path).stem
ext_name = Path(full_path).suffix
path = os.path.dirname(full_path)

 

10. UI로 tkinter 사용시 sub window를 만들고 해당 윈도우에 텍스트창을 넣고 스크롤바를 추가하여 그곳에 뭔가를 출력하고 싶을때

make sub window and text/scrollbar by tkinter

from tkinter import *
import tkinter as tk

root = Tk()
root.title("sub window test")
root.geometry("800x500+1000+200")
root.resizable(False, False)
root.configure(bg='white')

sub = tkinter.Toplevel(root)
sub.resizable(0,0)
sub.geometry("600x800+400+200")
sub.title("sub window")
sub.attributes('-topmost', 'true')  #창을 항상 위로 보이게 하고 싶을때

scbar = tkinter.Scrollbar(sub)
scbar.pack(side='right', fill='y')

sub_text = tkinter.Text(sub, width="580", height="780", yscrollcommand = scbar.set)
sub_text.pack()
scbar["command"]=sub_text.yview
sub_text.insert(tkinter.END, "")  #텍스트추가.

#추가한 텍스트가 많아져서 마지막 추가한 텍스트가 보이도록 하려면 아래 명령 이용
sub_text.see("end")
sub_text.update()

 

11. 하위폴더 전부를 돌면서 특정확장자를 가진 파일만을 골라서 무언가를 확인해야 할때

all sub folder traversal recursively and find specific file extension

from pathlib import Path

for (path, dir, files) in os.walk(os.getcwd()):
    for filename in files:
        ext = os.path.splitext(filename)[-1]
        if ext == ".xml":  
            xml_name = os.path.join(path, filename)
 			#블라블라~

 

12. Pyinsatller로 배포하기 어려울때 python은 설치되어있으나 특정 패키지를 코드안에서 알아서 설치해주고 싶을때

install specific package when run time

#예를 들어서 누군가에게 코드를 보내는데 paramiko 패키지가 필요한 코드인 경우 알아서 설치
#다만.. pip 경로는 path에 잡혀있어야 한다는 단점이 있음.

import subprocess
import sys

try:
    import paramiko
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install", "paramiko"])
finally:
    import paramiko

 

13. openpyxl 등으로 작업한 엑셀파일을 열고 싶을때

to open xls file when run time

#pywin32 설치필요
import win32com.client
import os

save_file_name = "" #열고싶은 excel파일지정

#아래 두가지 방법중 택일
#startfile의 경우는 스크립트가 끝나면 실행이 안되는 문제가 있으나
#win32com을 이용한 방법은 스크립트가 끝나도 엑셀이 열린상태로 있음
os.startfile(save_file_name)

excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
excel.Workbooks.Open(save_file_name)

 

14. openpyxl로 작업할때 컬럼이 AA혹은 AAA 를 넘는 경우 다음 컬럼을 리턴하는 함수(제가 봐도..좀 무식하게 작성하긴 했습니다..ㅎㅎ 더 좋은 방법이 있으면 리플주세요)

returrn next column string when using openpyxl

def get_next_column(current_column):
    if current_column == 'Z':
        next_column = 'AA'
    elif len(current_column) == 2:
        if current_column == "ZZ":
           next_column = "AAA" 
        elif current_column[1] == 'Z':
            next_column = chr(ord(current_column[0])+1) + 'A'
        else:
            next_column = current_column[0] + chr(ord(current_column[1]) +1 )
    elif len(current_column) ==3:
        if current_column[2] == 'Z':
            if current_column[1] =='Z':
                next_column = chr(ord(current_column[0])+1) +  'AA'
            else:
                next_column = current_column[0]+chr(ord(current_column[1])+1) + 'A'
        else:
            next_column = current_column[0] + current_column[1] + chr(ord(current_column[2]) +1 )
    else:
        next_column = chr(ord(current_column) +1 )
	return next_column

 

15. 빈파일을 생성하고 싶을때
to make empty file

with open('empty_file.txt', 'w'):
	pass

 

16. 읽어들인 json file을 decode한후 뭔가를 변경하고 나서 다시 저장할때(ensure_ascii=False는 한글이 제대로 저장되려면 필요하다.)
read json file and modify some infomation and write another json file

import json

with open('to_read.json', 'r', encoding='utf-8') as f:
	contents = f.read()
    json_data = json.loads(contents)
    
json_data['sample'] = 'sample'
with open('to_write.json', 'w', encoding='utf-8') as f:
	json.dump(json_data, f, ensure_ascii=False, indent='\t')

 

17. 폴더가 있는지 확인하고 특정폴더구조를 한번에 만들고 싶을때(/a/b/c 가 없을때 한번에 모두 a,b,c folder를 생성)
make directory structure

import os
testpath = 'c:\a\b\c'
if os.path.isdir(testpath) == False:
	os.makedirs(testpath)

 

18. openpyxl 사용시 스트링의 일부만 다른 폰트를(색상 볼드 등) 적용하여서 넣고 싶을때
when using openpyxl, use another font(color, bold etc) patially
https://openpyxl.readthedocs.io/en/stable/rich_text.html 참조

import openpyxl
from openpyxl.cell.text import InlineFont
from openpyxl.cell.rich_text import TextBlock, CellRichText

rtc = CellRichText()
rtc.append('This is the ')
ift = InlineFont(rFont='Arial', color='00FF0000', sz=12, b=True)
rtc.append(TextBlock(ift, 'TEST'))
ift = InlineFont(rFont='Arial', color='00000000', sz=12, b=True)
rtc.append(TextBlock(ift, ' example'))
worksheet['A1'] = rtc

 

19. openpyxl 사용시 데이터유효성 팝업을 보여주는 셀을 만들고 싶을 때.
주의할 점은 showDropDown을 false로 해야 유효성 팝업이 보여진다.(왜 반대인지는 모르겠음..)
when use openpyxl to show data validation dropdown popup.
Notice : To show dropdown popup set showDropDown variable set to False.

from openpyxl.worksheet.datavalidation import DataValidation

dv = DataValidation(type='list', formula1='"Sample1, Sample2"', allow_blank=False, showDropDown=False)
ws.add_data_validation(dv)
dv.add(ws['A1']) //add target cell

 

20. openpyxl 사용시 엑셀파일 정보의 속성을 수정하고 싶을 때
각각의 property 항목은 수정하면서 엑셀파일-정보-속성에서 확인하면 된다..
when use openpyxl, modify excel document property.

import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook

wb = Workbook()
wb.properties.title = 'sample'
wb.properties.description = 'sample'
wb.properties.company = 'sample'
wb.properties.category = 'sample'
wb.properties.subject = 'sample'
wb.properties.identifier = 'sample'
wb.properties.contentStatus = 'sample'
wb.properties.keywords = 'sample'
wb.properties.creator = 'sample'
wb.properties.lastModifiedBy = 'sample'

wb.save("sample.xlsx")

 

21.

 

추후 계속 업데이트 예정...

728x90

댓글