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

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.

Related

how to python win32com use eml file open outlook. attachment file extract and body content read

python win32com use open Outlook.Application. eml attachment files extract. and read subject and body content. use python native package use. eml file format.
Code
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
msg = outlook.OpenSharedItem("C:\\sample\\todo.eml")
print(msg)
error
Traceback (most recent call last):
File "init.py", line 4, in <module>
msg = outlook.OpenSharedItem("C:\\sample\\todo.eml")
File "<COMObject GetNamespace>", line 2, in OpenSharedItem
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096,
'Microsoft Outlook', 'Invalid path or URL.', None, 0, -2147352567), None)
python use eml file open win32com module to use.
any ideas to share

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 save file on XLWings

[USING XLWINGS PACKAGE]
I'm attempting to open an excel spreadsheet (existing), write data to specified cells, and then use the workbook.save() function to save the file to a new file name (as not to overwrite)
Right now I currently have:
app = xw.App(visible = False)
wbMain = wx.Book('Example.xlsm') #Open premade excel file
sheetMain = wbMain.sheets['Example']
sheetMain.range('A1').value = 'Test' #Modify value of cell A1
wbMain.save('NewFileName.xlsm') #Save to new filename
wbMain.close() #Close current excel sheet
app.kill() #Kill program (may not work)
(Sorry about my formatting if it's off)
Here is my traceback:
Traceback (most recent call last):
File "C:\Users\USER\Desktop\test_proj\main.py", line 34, in <module>
wbMain.save(NewFileName.xlsm)
----
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\main.py", line 688, in save
return self.impl.save(path)
---
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\_xlwindows.py", line 472, in save
self.xl.SaveAs(os.path.realpath(path))
----
File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-
packages\xlwings\_xlwindows.py", line 63, in __call__
v = self.__method(*args, **kwargs)
---
File "<COMObject Open>", line 7, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft
Excel', 'SaveAs method of Workbook class failed', 'xlmain11.chm', 0,
-2146827284), None)
I've tried lookin at the XLWings documentation and various other stackoverflow threads but none seemed to offer a solution that worked. Has anyone had the same issue before?
I had the same problem - turns out using the full path in wbMain.save('C:/xxx/NewFileName.xlsm') worked for me.
Credits to #aneroid for the help! See here: xlwings: Save and Close

Opening Word from Python, unexpected behaviour

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)

Remove AD user from Security group using Python

I am trying to remove a user from a security group using Python and pywin32, but so far have not been successful. However I am able to add a user to a security group.
from win32com.client import GetObject
grp = GetObject("LDAP://CN=groupname,OU=groups,DC=blah,DC=local")
grp.Add("LDAP://CN=username,OU=users,DC=blah,DC=local") # successfully adds a user to the group
grp.Remove("LDAP://CN=username,OU=users,DC=blah,DC=local") # returns an error
The error is below:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<COMObject LDAP://CN=groupname,OU=groups,DC=blah,DC=local>", line 2, in Remove
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
0, -2147024891), None)
I have also tried adding using GetObject to get the user and remove it that way, however I get the same error.
usr = GetObject("LDAP://CN=user,OU=users,DC=blah,DC=local")
grp.Remove(usr)
Any help would be much appreciated as I've hit a dead-end here.
EDIT
I have also now tried using Tim Golden's active_directory module to try and remove the group member.
import active_directory as ad
grp = ad.find_group("groupname")
usr = ad.find_user("username")
grp.remove(usr.path())
However this also doesn't work, and I encounter the below error.
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\active_directory.py", line 799, in __getat
tr__
attr = getattr(self.com_object, name)
AttributeError: 'PyIADs' object has no attribute 'group'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\active_directory.py", line 802, in __getat
tr__
attr = self.com_object.Get(name)
pywintypes.com_error: (-2147463155, 'OLE error 0x8000500d', (0, 'Active Director
y', 'The directory property cannot be found in the cache.\r\n', None, 0, -214746
3155), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python33\lib\site-packages\active_directory.py", line 1081, in remove
self.group.Remove(dn)
File "C:\Python33\lib\site-packages\active_directory.py", line 804, in __getat
tr__
raise AttributeError
AttributeError
EDIT
Wherby suggested that I change to Python 2.7 and give that a go. I have just tried this:
import active_directory as ad
user = ad.find_user("username")
group = ad.find_group("groupname")
group.remove(user.path())
... but I'm still getting an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<COMObject LDAP://CN=groupname,OU=groups,DC=blah,DC=local>", line 2, in remove
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
0, -2147024891), None)
The user and group are definitely found correctly, as I can print their LDAP paths using print user.path() and print group.path()
Are there any other active directory libraries for Python 3.3 that anyone can recommend?
From
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\active_directory.py", line 799, in __getat
tr__
attr = getattr(self.com_object, name)
AttributeError: 'PyIADs' object has no attribute 'group'
The error indicate you are using not existed "group name", the function find_group required anexisted group name, but you give not existed name.
You should double check "Tim Golden's active_directory module" 's manual.
For
usr = GetObject("LDAP://CN=user,OU=users,DC=blah,DC=local")
grp.Remove(usr)
I suggest you add "print user" to see if the user really get.
Well, I've gone and figured out I was being a bit of a muppet. The account I was logged in to didn't have the permissions to delete from AD groups. When I logged in as the network admin account it worked like a charm.
The final code:
from win32com.client import GetObject
group = GetObject("LDAP://CN=groupname,OU=Groups,DC=blah,DC=local")
group.Remove("LDAP://CN=username,OU=Users,DC=blah,DC=local")

Categories