Python ☞ day 10

Python 학습 노트 의 자동화 사무 와 마우스 키보드 시 뮬 레이 션
csv 파일 읽 기
  • csv 파일 읽 기
  • import csv
    
    def readCsv(path):
        infoList = []
        with open(path, "r") as f:
            allFileInfo = csv.reader(f)
            for row in allFileInfo:
                infoList.append(row)
        return infoList
    
    path = r"C:\Users\xlg\Desktop\Python-1704\day15\2、  csv  \000001.csv"
    info = readCsv(path)
    
  • csv 파일 쓰기
  • import csv
    
    def writeCsv(path, data):
        with open(path, "w") as f:
            writer = csv.writer(f)
            for rowData in data:
                print("rowData = ", rowData)
                writer.writerow(rowData)
    
    
    path = r"C:\Users\xlg\Desktop\Python-1704\day15\2、  csv  \000002.csv"
    writeCsv(path, [["1","2","3"],["4","5","6"],["7","8","9"]])
    

    PDF 파일 읽 기
    import sys
    import importlib
    importlib.reload(sys)
    
    from pdfminer.pdfparser import PDFParser, PDFDocument
    from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
    from pdfminer.converter import PDFPageAggregator
    from pdfminer.layout import LTTextBoxHorizontal, LAParams
    from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
    
    def readPDF(path, toPath):
        #        pdf  
        f = open(path, "rb")
    
        #    pdf     
        parser = PDFParser(f)
        #  pdf  
        pdfFile = PDFDocument()
        #          
        parser.set_document(pdfFile)
        pdfFile.set_parser(parser)
        #       
        pdfFile.initialize()
        #        txt  
        if not pdfFile.is_extractable:
            raise PDFTextExtractionNotAllowed
        else:
            #    
            #     
            manager = PDFResourceManager()
            #    PDF    
            laparams = LAParams()
            device = PDFPageAggregator(manager, laparams=laparams)
            #     
            interpreter = PDFPageInterpreter(manager, device)
            #      ,      
            for page in pdfFile.get_pages():
                interpreter.process_page(page)
                layout = device.get_result()
                for x in layout:
                    if (isinstance(x, LTTextBoxHorizontal)):
                        with open(toPath, "a") as f:
                            str = x.get_text()
                            #print(str)
                            f.write(str+"
    ") path = r"C:\Users\xlg\Desktop\Python-1704\day15\3、 PDF \sunck.pdf" toPath = r"C:\Users\xlg\Desktop\Python-1704\day15\3、 PDF
    .txt" readPDF(path, toPath)

    워드 파일 읽 기
  • doc 와 docx 파일 읽 기
  • import win32com
    import win32com.client
    
    def readWordFile(path):
        #    word  ,    doc docx    
        mw = win32com.client.Dispatch("Word.Application")
        #    
        doc = mw.Documents.Open(path)
        for paragraph in doc.Paragraphs:
            line = paragraph.Range.Text
            print(line)
        #    
        doc.Close()
        #  word
        mw.Quit()
    
    path = r"C:\Users\xlg\Desktop\Python-1704\day15\4、word     \sunck.doc"
    readWordFile(path)
    
  • doc 와 docx 파일 을 읽 고 다른 파일 에 쓰기
  • import win32com
    import win32com.client
    
    def readWordFileToOtherFile(path, toPath):
        mw = win32com.client.Dispatch("Word.Application")
        doc = mw.Documents.Open(path)
    
        # word           
        doc.SaveAs(toPath, 2)#2   txt  
    
        doc.Close()
        mw.Quit()
    
    path = r"C:\Users\xlg\Desktop\Python-1704\day15\4、word     \sunck.doc"
    toPath = r"C:\Users\xlg\Desktop\Python-1704\day15\4、word     \a.txt"
    readWordFileToOtherFile(path, toPath)
    
  • 워드 파일 만 들 기
  • import win32com
    import win32com.client
    import os
    
    def makeWordFile(path, name):
        word = win32com.client.Dispatch("Word.Application")
        #     
        word.Visible = True
    
        #    
        doc = word.Documents.Add()
    
        #   
        #     
        r = doc.Range(0, 0)
        r.InsertAfter("   "+ name + "
    ") r.InsertAfter(" ……
    ") # doc.SaveAs(path) # doc.Close() # word word.Quit() names = [" ", " ", " "] for name in names: path = os.path.join(os.getcwd(), name) makeWordFile(path, name)

    엑셀 파일 읽 기
  • xlsx 파일 읽 기
  • #  xlsx   xls
    # openpyxl  ->  xlsx
    
    from openpyxl.reader.excel import load_workbook
    
    def readXlsxFile(path):
        #    
        file = load_workbook(filename=path)
        #       
        #print(file.get_sheet_names())
        sheets = file.get_sheet_names()
    
        #      
        sheet = file.get_sheet_by_name(sheets[0])
        #    
        #print(sheet.max_row)
        #    
        #print(sheet.max_column)
        #  
        #print(sheet.title)
    
    
    
        for lineNum in range(1, sheet.max_row + 1):
            #print(lineNum)
            lineList = []
            #print(sheet.max_row, sheet.max_column)
            for columnNum in range(1, sheet.max_column + 1):
                #   
                value = sheet.cell(row=lineNum, column=columnNum).value
                #if value != None:
                lineList.append(value)
    
            print(lineList)
    
    
        #        
    
    #    xls  
    path = r"C:\Users\xlg\Desktop\Python-1704\day15\5、excel     \sunck.xlsx"
    readXlsxFile(path)
    
  • 전체 xlsx 데이터 되 돌려 주기
  • #  xlsx   xls
    # openpyxl  ->  xlsx
    
    from openpyxl.reader.excel import load_workbook
    
    def readXlsxFile(path):
        dic = {}
        file = load_workbook(filename=path)
        sheets = file.get_sheet_names()
        print(len(sheets))
    
        for sheetName in sheets:
            sheet = file.get_sheet_by_name(sheetName)
            #        
            sheetInfo = []
            for lineNum in range(1, sheet.max_row + 1):
                lineList = []
                for columnNum in range(1, sheet.max_column + 1):
                    value = sheet.cell(row=lineNum, column=columnNum).value
                    lineList.append(value)
                sheetInfo.append(lineList)
    
            #           
            dic[sheetName] = sheetInfo
        return dic
    
    #    xls  
    path = r"C:\Users\xlg\Desktop\Python-1704\day15\5、excel     \sunck.xlsx"
    dic = readXlsxFile(path)
    print(dic["    "])
    print(len(dic))
    
  • xls 와 xlsx 파일 내용 되 돌려 주기
  • #    
    from collections import OrderedDict
    
    #    
    from pyexcel_xls import get_data
    
    
    def readXlsAndXlsxFile(path):
        dic = OrderedDict()
        #    
        xdata = get_data(path)
        for sheet in xdata:
            dic[sheet] = xdata[sheet]
        return dic
    
    
    path = r"C:\Users\xlg\Desktop\Python-1704\day15\5、excel     \sunck.xls"
    dic = readXlsAndXlsxFile(path)
    print(dic)
    print(len(dic))
    
  • xls 파일 쓰기
  • #    
    from collections import OrderedDict
    #    
    from pyexcel_xls import save_data
    
    
    def makeExcelFile(path, data):
        dic = OrderedDict()
        for sheetName, sheetValue in data.items():
            d = {}
            d[sheetName] = sheetValue
            dic.update(d)
    
        save_data(path, dic)
    
    
    path = r"C:\Users\xlg\Desktop\Python-1704\day15\5、excel     \b.xls"
    makeExcelFile(path, {" 1":[[1,2,3],[4,5,6],[7,8,9]],
                         " 2": [[11, 22, 33], [44, 55, 66], [77, 88, 99]]})
    
    

    ppt 파일
  • ppt 파일 쓰기
  • import win32com
    import win32com.client
    
    def makePPT(path):
        ppt = win32com.client.Dispatch("PowerPoint.Application")
        ppt.Visible = True
    
        #      
        pptFile = ppt.Presentations.Add()
    
        #       1   ( 1  )    2   
        page1 = pptFile.Slides.Add(1,1)
        t1 = page1.Shapes[0].TextFrame.TextRange
        t1.Text = "sunck"
        t2 = page1.Shapes[1].TextFrame.TextRange
        t2.Text = "sunck is a good man"
    
        page2 = pptFile.Slides.Add(2, 1)
        t3 = page2.Shapes[0].TextFrame.TextRange
        t3.Text = "kaige"
        t4 = page2.Shapes[1].TextFrame.TextRange
        t4.Text = "kaige is a good man"
    
        page2 = pptFile.Slides.Add(3, 2)
    
        #  
        pptFile.SaveAs(path)
        pptFile.Close()
        ppt.Quit()
    
    
    
    path = r"C:\Users\xlg\Desktop\Python-1704\day15\6、ppt     \sunck.ppt"
    makePPT(path)
    

    음악 을 틀다
    import time
    import pygame
    #pip  install  pygame
    
    #    
    filePath = r"C:\Users\xlg\Desktop\Python-1704\day15\7、    \res\0.mp3"
    
    #   
    pygame.mixer.init()
    #    
    track = pygame.mixer.music.load(filePath)
    #  
    pygame.mixer.music.play()
    #
    time.sleep(5)
    #  
    pygame.mixer.music.stop()
    

    데스크 톱 배경 그림 수정
    #win +r -> regedit -> HKEY_CURRENT_USER -> Control panel ->Desktop
    
    import win32api
    import win32con
    import win32gui
    
    def setWallPaper(path):
        #     
        reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
    
        #2     0      6      10  
        win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
        #
    
        #SPIF_SENDWININICHANGE      
        win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, path, win32con.SPIF_SENDWININICHANGE)
    
    setWallPaper(r"C:\Users\xlg\Desktop\Python-1704\day15\8、      \res\6.jpg")
    

    키보드 시 뮬 레이 션
    import win32con
    import win32api
    import time
    
    '''
    win32api.keybd_event(91,0,0,0)
    time.sleep(0.1)
    win32api.keybd_event(91,0,win32con.KEYEVENTF_KEYUP,0)
    '''
    while True:
        win32api.keybd_event(91, 0, 0, 0)
        time.sleep(0.1)
        win32api.keybd_event(77, 0, 0, 0)
        time.sleep(0.1)
        win32api.keybd_event(77, 0, win32con.KEYEVENTF_KEYUP, 0)
        win32api.keybd_event(91, 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(3)
    

    마우스 시 뮬 레이 션
    import win32con
    import win32api
    import time
    
    #       
    win32api.SetCursorPos([30, 40])
    time.sleep(0.1)
    
    #      
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0)
    #      
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0)
    

    좋은 웹페이지 즐겨찾기