Python Forum

Full Version: Cannot open file in an OpenSharedItem() iterator - The file may not exist/may be open
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to run the following code in Python:

for filename in os.listdir(workdir1):
msg=outlook.OpenSharedItem(workdir1 + filename)
if str(msg.Body).find("TestString"):
myfile = open(workdir + "results.txt", 'w')
myfile.write("%s\n" % filename)
myfile.close()
However, I keep getting the following error:

com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Cannot open file: N:\emails\TEST1.msg. The file may not exist, you may not have permission to open it, or it may be open in another program. Right-click the folder that contains the file, and then click Properties to check your permissions for the folder.', None, 0, -2147287008), None)

Note that TEST1.msg does exist, but when I try to delete it from the directory I get 'file opened in another program (Python)' error. Seems like that file is constantly opened...

How can I run my code whilst remediating this issue (e.g. iterate over every file in the test directory and write results of a search function)?

Thanks a lot!
Please, edit your post using the tags (python code, output and error).
With tags it becomes more clear for us to help you.
Apologies, I am new to these boards and hence lack proper syntax...

for filename in os.listdir(workdir1):
msg=outlook.OpenSharedItem(workdir1 + filename)
if str(msg.Body).find("TestString"):
myfile = open(workdir + "results.txt", 'w')
myfile.write("%s\n" % filename)
myfile.close()
Error:
com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Cannot open file: N:\emails\TEST1.msg. The file may not exist, you may not have permission to open it, or it may be open in another program. Right-click the folder that contains the file, and then click Properties to check your permissions for the folder.', None, 0, -2147287008), None)
I think the error is here:

msg=outlook.OpenSharedItem(workdir1 + filename)
Check if the path workdir1 + filename is really the path of the wanted file. Try to add '/' between them.
Another thing is that you use workdir1 and then workdir. Is this right?