0

I am running a script that creates a workbook, write some data into it then saves it.

At the end of my script I have:

workbook.SaveAs('tempfile.xlsx')

But what is happening is that it keeps saving to some obscure directory, where earlier today I downloaded an excel file from a sharepoint site. So I tried:

import os
os.chdir('C:/mydir')

Then I run the script and it still saves to the obscure directory. I type in os.getcwd() into IDLE prompt and it returns 'C:/mydir.'

Cannot figure out how to get this saving properly. When I try:

workbook.SaveAs('C:/mydir/tempfile.xlsx')

I get an error:

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Office         Excel', "Microsoft Office Excel cannot access the file   'C:\\weird dir\\//mydir/FC424E40'. There are several possible reasons:\n\n• The file name or path does not exist.\n• The file is being used by another program.\n• The workbook you are trying to save has the same name as a currently open workbook.", 'C:\\Program Files (x86)\\Microsoft Office\\Office12\\1033\\XLMAIN11.CHM', 0, -2146827284), None)

I know this is probably a simple fix but I can't figure it out. Any ideas?

Simon Adcock
  • 3,554
  • 3
  • 25
  • 41
griffsterb
  • 131
  • 4
  • 12
  • Did you try `workbook.SaveAs(r'C:\mydir\tempfile.xlsx')`? Maybe back-slashes will help... – rodrigo Nov 14 '13 at 23:20
  • @rodrigo Backslashes did seem to work. Thanks! What does the 'r' do before the directory? My code seems to work without that. – griffsterb Nov 14 '13 at 23:24
  • @user2941919 the backslash is used to escape some characters in Python strings... eg, `\t` is tab and `\n` is a new line... When using backslashes purely for back slashes, then you use `r` as a prefix to indicate that behaviour should not take place – Jon Clements Nov 14 '13 at 23:27

1 Answers1

1

If you are using pywintypes (or pywin32) you are bound to how Excel understands the commands your call on its COM API. This is in no way linked to the current directory where python executes. Failing to have a current directory, Excel will select one (using its own "rule of least surprise"...) which appears to be the last directory from where you opened an Excel file. As rodrigo suggested, you'd better use full path to tell Excel where to save.

Cilyan
  • 7,883
  • 1
  • 29
  • 37