0

I'm trying to use Python to paste a filepath string into Excel. Specifically I'm pasting into the "File name:" section of the file explorer after using Save As. Below is the section of code I used to paste the filepath and save the file.

    # TODO implement save functionality
    fileName = os.getcwd() + r'\bracReg.csv'
    pc.copy(fileName)
    pyautogui.write(pc.paste())
    pause()
    pyautogui.press(['tab', 'c', 'c', 'enter', 'tab', 'enter'], interval=.1)
    xw.apps.active.api.Quit()

When I check my clipboard it has the correct filepath and if I manually paste it in then it saves just fine. However, what's weird is the filepath that is pasted in the textbox by the script is missing the initial drive letter. So instead of "C:\blah\whatever" it pastes ":\blah\whatever". I'm pasting the full function code below in case this some weird interaction with xlwings, but any other suggestions are welcome because I'm a bit stumped.

def create_bracket_registration():
    # create instance of Excel App
    app = xw.App()
    # create variables for associated book and sheet
    wb = app.books['Book1']
    ws = wb.sheets('Sheet1')
    # insert headings
    ws.range('A1').value = ['First', 'MI', 'Last', 'Nick', 'Vintage', 'Lane number', 'Play position', 'Avg', 'Hbrac', 'Sbrac']
    # somehow detects last column of data idk
    last_column = ws.range(1, 1).end('right').get_address(0, 0)[0]
    ws.range('A:{}'.format(last_column)).api.ColumnWidth = 13
    AppHandler.focus_on_window('.*Excel*')
    # move cursor to desired data entry position
    pyautogui.press('enter')
    pause()
    # TODO implement save functionality
    fileName = os.getcwd() + r'\bracReg.csv'
    pc.copy(fileName)
    pyautogui.write(pc.paste())
    pause()
    pyautogui.press(['tab', 'c', 'c', 'enter', 'tab', 'enter'], interval=.1)
    xw.apps.active.api.Quit()

PS: I'm aware there are almost certainly better ways to do this, but at this point I'm just interested in explaining this behavior

  • To the extent I can replicate your operation I could not duplicate the issue. Why are you using pyautogui? is it to save as CSV? perhaps you'd be better to look at the checked answer on this question; **https://stackoverflow.com/questions/68818825/xlwings-is-it-possible-to-save-file-as-csv** – moken Jun 13 '22 at 07:45
  • Please post a minimal reproducible example - something we can just copy and paste and debug the code directly. https://stackoverflow.com/help/minimal-reproducible-example – GordonAitchJay Jun 13 '22 at 12:48

0 Answers0