Opening Word from Python, unexpected behaviour - python

I'm writing a script to parse word document and get certain outputs. I use the following commands for reading the desired document.
import win32com.client as win32
import Tkinter,tkFileDialog
root = Tkinter.Tk()
root.withdraw()
filename = tkFileDialog.askopenfilename() # getting filename through windows explorer
word = win32.Dispatch("Word.Application")
#word.Documents.Open(filename)
The last line which is commented is how I was planning to implement this. But whenever I try to open a file which has a space in it's filename, this fails. In fact I found that if I give word.Documents.Open("C:/Python27/word sample.docm")
This will also fail, but if I use backslash after C: it'll work perfectly.
In short the below commands for opening document will work:
word.Documents.Open("C:\Python27/word sample.docm")
word.Documents.Open(filename) #if filename don't have a space
And the below ones will not work:
word.Documents.Open("C:/Python27/word sample.docm")
word.Documents.Open(filename) #filename have a space in it
Could someone explain what is going wrong here?
This is the error that I'm receiving:
C:\Users\xxx>C:\Python27\python.exe C:\Python27\test.py
Traceback (most recent call last):
File "C:\Python27\test.py", line 10, in <module>
word.Documents.Open("C:/Python27/word sample.docm")
File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Word'
, u'This file could not be found.\r (C:\\//Python27/word%20sample.docm)', u'
wdmain11.chm', 24654, -2146823114), None)

Related

Python docx2pdf Convert Com_Error

I want to convert 2 docx files (which are in same path) in same code.
Yesterday it was working. But today i have an error. Still it's working, it convert files but it stop the code on that cell '''docx2pdf.convert(path)''' and i have different codes after it, code must continue.
I didn't change anything.
Error is:
**0%| | 0/4 [00:00<?, ?it/s]
Traceback (most recent call last):
File "C:\Users\username\word_automation\example.py", line 372, in convert("C:/Users/username/word_automation/")
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\docx2pdf_init_.py", line 106, in convert return windows(paths, keep_active)
File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\docx2pdf_init_.py", line 25, in Windows doc = word.Documents.Open(str(docx_filepath))
File "<COMObject >", line 5, in Open
com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Word', 'Dosya bozuk görünüyor.', 'wdmain11.chm', 25272,-2146822496), None)**
How can i fix this?
Thanks for your help.
-2146822496 is 0x800A16A0, which is "the file appears to be damaged". If you can open this file in Word, try doing a "save as" and replacing the original.
I solved the error.
My program makes new word files from another word files. And one of the new word file left a hidden broken word file which name is $new.docx. And i can't see it even open hidden files.
I searched it and i saw, i should write to cmd attrib -h -r -s /s /d C:\*.* for be appear hidden files. And in programs folder, it appeared.
I deleted it, error fixed.

trying out "win32com.client" but it cannot find my file

I'm using openpyxl to modify some excel document but it doesn't actualize the calculated cells inside that document. It seems I must open the document with excel. I found this link.
But it fails finding my document. How is that possible? Could someone help on that specific point please?
Here is what I get:
>>> os.listdir()
['R_F.xlsx']
>>> import win32com.client
>>> xl = win32com.client.DispatchEx("Excel.Application")
>>> wb = xl.workbooks.open("R_F.xlsx")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<COMObject <unknown>>", line 2, in open
pywintypes.com_error: (-2147352567, 'Une exception s’est produite.', (0, 'Microsoft Excel', "Désolé... Nous ne trouvons pas R_F.xlsx. Peut-être l'avez-vous déplacé, renommé ou supprimé\xa0?", 'xlmain11.chm', 0, -2146827284), None)`
Same does happen when trying to open a word document. It doesn't find it! Very strange.

Running an Excel macro via Python? (New problem - saving)

I already saw this question in other link but I'm new here and i don't have reputation to comment there.
I made the script works and the macro run but when saving the file instead of just saving, it opens a excel pop-up asking if i confirm the changes. How do I save directly without opening this pop-up?
my code (edited):
import os.path
import win32com.client as wincl
if os.path.exists("C:\\Users\\peo_cpena\\Downloads\\excel.xlsx"):
try:
xl = wincl.Dispatch("Excel.Application")
xl.Workbooks.Open(os.path.abspath(
"C:\\Users\\peo_cpena\\Downloads\\excel.xlsx"))
xl.Application.Run("macro2.xlsm!Macro2")
xl.Application.Workbooks("excel.xlsx").Save()
xl.Application.DisplayAlerts = False
xl.Application.Workbooks("excel.xlsx").Quit(False)
del xl
except:
xl.Application.Quit()
print("It didn't work")
del xl
Removing the Try i received this error:
Traceback (most recent call last):
File "C:/Users/peo_cpena/PycharmProjects/Cursoemvideo/UOL/CalculoImpARG.py", line 14, in <module>
xl.Application.Workbooks("C:\\Users\\peo_cpena\\Downloads\\Vendas_por_Repasse_Aeria_Games_Europe_GmbH_01102020-31102020.xlsx").Save()
File "C:\Users\peo_cpena\PycharmProjects\Cursoemvideo\venv\lib\site-packages\win32com\client\dynamic.py", line 197, in __call__
return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
pywintypes.com_error: (-2147352567, 'Exceção.', (0, None, None, None, 0, -2147352565), None)
Try explicitly saving the workbook before closing it:
xl.Application.Workbooks("excel.xlsx").Save()
xl.Application.Workbooks("excel.xlsx").Close(False)

unable to create a text file using python

I am trying to learn the file I/O in python, I am trying following code to generate a text file in D drive of my computer with the statements written in the code but the compilation fails saying that the file 'I want to create' is not available which is obvious. How to create the file then?
file = open(r'D:/pyflie/text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
and the error shown is
C:\Users\ssgu>python D:/pyfile/fw.py
Traceback (most recent call last):
File "D:/pyfile/fw.py", line 1, in <module>
file = open(r'D:/pyflie/text.txt',"w")
FileNotFoundError: [Errno 2] No such file or directory:
'D:/pyflie/text.txt'
You will get such an error if one of the specified directories does not exist. In this case, D:/pyflie/ does not exist yet, so it must be created beforehand. Then, your code should create and open the file normally. You can check upfront:
import os
if not os.path.exists(r"D:\pyflie"):
os.makedirs(r"D:\pyflie")
file = open(r'D:\pyflie\text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
Also, check for typos in the path name. Did you mean D:/pyfile/?

Running VBA code from Python: macros may be disabled

Trying to run an Excel macro via Python I get the following error:
Traceback (most recent call last):
File ".\test.py", line 17, in <module>
xlApp.Application.Run(MACRO)
File "<COMObject <unknown>>", line 14, in Run
File "C:\Users\twauchop\Desktop\Python\virtual_envs\gutenberg\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Cannot run the macro 'test'. The macro may not be available in this workbook or all macros may be disabled.", 'xlmain11.chm', 0, -2146827284), None)
I tried many of the fixes suggested in other questions.
I tried 'xlApp.Application.Run(wb.name + "!" + MACRO)'.
Is this a naming convention issue? I enabled everything via Trust Center and changed the VBA sub to public.
As a side-note, I also cannot run macros from the programmatically opened workbook (i.e. if I try manually). If I open the workbook manually, however, everything is fine.
I am running Python 3.6.5 on a 64 bit system, Windows 10.
Python:
import win32com.client
import os
import traceback
DIRECTORY = r'C:\\Users\\twauchop\\Desktop\\Excel\\'
FILE = 'test.xlsb'
MACRO = 'test'
path = os.path.join(DIRECTORY, FILE)
if os.path.exists(path):
try:
xlApp = win32com.client.Dispatch('Excel.Application')
xlApp.DisplayAlerts = False
xlApp.Visible = True
wb = xlApp.Workbooks.Open(Filename=path, ReadOnly=1)
xlApp.Application.Run(MACRO)
wb.Close(SaveChanges=1)
xlApp.Application.Quit()
print('Code ran successfully.')
except:
print('An error was encountered; see traceback.')
print(traceback.format_exc())
xlApp.Quit()
VBA:
Public Sub test()
MsgBox "Hello World!"
End Sub
xlApp.Application.AutomationSecurity=1 needs to go before ANY xlApp.Application.Run(excelMacroNameHere) code, as the AutomationSecurity is used to control (enable vs disable) macros and 1 means enable all macros.

Categories