I have an outlook file saved locally. I am using filedialog.askopenfile to ask the user to direct the script to the file, this works fine.
However when I then try to check the receive date of the file I am getting the following error:
com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', "We can't open 'Desktop/emails/email.msg'. It's possible the file is already open, or you don't have permission to open it.\n\nTo check your permissions, right-click the file folder, then click Properties.", None, 0, -2147287038), None)
I think the issue is that I am opening the file when I ask the User to point to the file and then trying to open it again with msg = outlook.OpenSharedItem(dir1) but I don't know how to resolve this.
My Code
from tkinter import *
# import filedialog module
from tkinter import filedialog
from tkinter import ttk
def your_script(dir1):
## Import Libraries
import pandas as pd
import numpy as np
from pandas import DataFrame
import win32com.client as client
import pathlib
import win32com.client
import datetime
from datetime import datetime
from time import strftime
######################################################################################################################
######################################################################################################################
outlook = win32com.client.Dispatch('Outlook.Application').GetNamespace('MAPI')
# Open email
msg = outlook.OpenSharedItem(dir1)
#Get email receive date
dt = msg.ReceivedTime
dt = datetime.strptime('2021-01-16', '%Y-%m-%d')
dt = dt.strftime('%d-%b-%Y')
dt
# Ask User to point to file
dir1 = filedialog.askopenfile(mode="r", initialdir="/", title="select the first file",
filetypes=(("Last quarters email", "*.msg"), ("all files", "*.*")))
your_script(dir1)
As #TheLizzard wrote, you are passing a fileobject to your function, but are expecting a path.
This returns the fileobject
filedialog.askopenfile()
Whereas this returns the path to the file
filedialog.askopenfilename()
your
outlock.OpenSharedItem(dir1)
wants a filepath not a fileobject
The error is STG_E_FILENOTFOUND, whcih means there is no file with the given name. You must pass a string with the fully qualified file name, not an object.
Related
I have the following python code and it runs just fine if I run it manually. When I go to schedule it in Window's scheduler it doesn't work. Any idea why?
#Data
from datetime import date, datetime, timedelta
import os
import sys
import traceback
#Pandas and Numpy
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import numpy as np
#Set Directory
#print('\nRead in data file')
indirname = r'C:/Users/user/Desktop'
outdirname = r'C:/Users/user/Desktop'
#Read in file
data_file = os.path.join(indirname, r'File Name.xlsx')
df = pd.read_excel(data_file, sheet_name='Sheet2', skiprows=range(1))
df.to_excel('C:/Users/user/Desktop/test5.xlsx')
If your script is fine than you can check your python.exe location using where python command in your command prompt then paste the path in Program/script dilogue box then provide full path of your python file in add arguments with double quotes. e.g. "C:\user\name\folder\file.py" and empty your start in (optional)
With excel already open, at the end of some code I am simply trying to open 2 excel files using the following code. However, nothing loads!
from urllib.request import urlopen
from bs4 import BeautifulSoup
import csv
import datetime
import openpyxl
import time
openPythonQuoteLS = openpyxl.load_workbook('c:\ls_equity\quote\PythonQuoteLS.xlsx')
openQuoteLS = openpyxl.load_workbook('c:\ls_equity\quote\QuoteLS.xlsm')
If all you want to do is open files in Excel, you can just use the OS library to send the command to the OS to open the file, as Aran-Fey mentioned above.
For your specific files:
import os
# ...
os.system('start excel.exe c:\ls_equity\quote\PythonQuoteLS.xlsx')
os.system('start excel.exe c:\ls_equity\quote\QuoteLS.xlsm')
I have a problem connecting to Excel API in windows 10. I use Office365 and with it Excel2016. My goal is: to download CSV file from a client FTPS Server, merge it with the existing files,perfom some action on it(with pandas) and then load the whole data into excel and do reporting with it... Up to the point of loading it into Excel everything is fine.I managed to do all steps automatically with Python (sorry if my code looks a little cluttered - I am new to Python)
import subprocess
import os
import ftplib
import fnmatch
import sys
from ftplib import FTP_TLS
from win32com.client import Dispatch
import pandas as pd
filematch = '*.csv'
target_dir = 'cannot tell you the path :-) '
def loginftps(servername,user,passwort):
ftps = FTP_TLS(servername)
ftps.login(user=user,passwd=passwort)
ftps.prot_p()
ftps.cwd('/changes to some directory')
for filename in ftps.nlst(filematch):
target_file_name = os.path.join(target_dir,os.path.basename(filename))
with open(target_file_name,'wb') as fhandle:
ftps.retrbinary('RETR %s' %filename, fhandle.write)
def openExcelApplication():
xl = Dispatch("Excel.Application")
xl.Visible = True # otherwise excel is hidden
def mergeallFilestoOneFile():
subprocess.call(['prepareData_executable.bat'])
def deletezerorows():
rohdaten = pd.read_csv("merged.csv",engine="python",index_col=False,encoding='Latin-1',delimiter=";", quoting = 3)
rohdaten = rohdaten.convert_objects(convert_numeric=True)
rohdaten = rohdaten[rohdaten.UN_PY > 0]
del rohdaten['deletes something']
del rohdaten['deletes something']
rohdaten.to_csv('merged_angepasst.csv',index=False,sep=";")
def rohdatenExcelAuswertung():
csvdaten = pd.csv_read("merged.csv")
servername = input("please enter FTPS serveradress:")
user = input("Loginname:")
passwort = input("Password:")
loginftps(servername,user,passwort)
mergeallFilestoOneFile()
deletezerorows()
And here I am stuck somehow,.. I did extensive google research but somehow nobody has ever tried to perform Excel tasks from within Python??
I found this stackoverflow discussion: Opening/running Excel file from python but I somehow cannot figure out where my Excel-Application is stored to run code mentioned in this thread.
What I have is an Excel-Workbook which has a data connection to my CSV file. I want Python to open MS-Excel, refresh data connection and refresh a PivoTable & then save and close the file.
Has anybody here ever tried to to something similar and can provide some code to get me started?
Thanks
A small snippet of code that should work for opening an excel file, updating linked data, saving it, and finally closing it:
from win32com.client import Dispatch
xl = Dispatch("Excel.Application")
xl.Workbooks.Open(Filename='C:\\Users\\Xukrao\\Desktop\\workbook.xlsx', UpdateLinks=3)
xl.ActiveWorkbook.Close(SaveChanges=True)
xl.Quit()
I am trying to use win32com to convert multiple xlsx files into xls using the following code:
import win32com.client
f = r"./input.xlsx"
xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open(f)
xl.ActiveWorkbook.SaveAs("./somefile.xls", FileFormat=56)
which is failing with the following error:
Traceback (most recent call last):
File "xlsx_conv.py", line 6, in <module>
xl.ActiveWorkbook.SaveAs("./somefile.xls", FileFormat=56)
File "C:\python27\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x9.py", line 46413, in SaveAs
, Local, WorkIdentity)
pywintypes.com_error: (-2147352562, 'Invalid number of parameters.', None, None)
Some more details:
I can do other commands to the workbook i.e. wb.Worksheets.Add()and set xl.Visible=True to view the workbook. and even do wb.Save() but can't do a wb.SaveAs()
The COM exception is due to the missing filename argument as f = r"./input.xlsx" cannot be found. Had you used Excel 2013+, you would have received a more precise exception message with slightly different error code:
(-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Sorry, we
couldn't find ./input.xlsx. Is it possible it was moved,
renamed or deleted?", 'xlmain11.chm', 0, -2146827284), None)
While your path does work in Python's native context pointing to the directory the called .py script resides, it does not in interfacing with an external API, like Windows COM, as full path is required.
To resolve, consider using Python's built-in os to extract the current directory path of script and concatenate with os.path.join() in the Excel COM method. Also, below uses try/except/finally to properly end the Excel.exe process in background regardless if exception is raised or not.
import os
import win32com.client as win32
cd = os.path.dirname(os.path.abspath(__file__))
try:
f = os.path.join(cd, "input.xlsx")
xl = win32.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open(f)
xl.ActiveWorkbook.SaveAs(os.path.join(cd, "input.xls"), FileFormat=56)
wb.Close(True)
except Exception as e:
print(e)
finally:
wb = None
xl = None
I spent quite a lot of time searching for a proper solution but the only thing I found out is that the script I wrote yesterday today is not working. In addition the same script works on other computers, so I guess this is something broken in the windows/MsExcel/Python environment, but I can't figure out where.
I found a work around to the "SaveAs" problem and it is just to use the "Save" function. Luckily that still works and does not block me from carrying on with my tasks. I hope this help.
import win32com.client as win32
from shutil import copyfile
# you need to define these two:
# src, is the absolute path to the excel file you want to open.
# dst, is the where you want to save as the file.
copyfile(src, dst)
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(PATH_DATASET_XLS)
ws = wb.Worksheets(DATASET_WORKING_SHEET)
# do some stuff
ws.Cells( 1, 'A' ).Value = "hello"
# Saving changes
wb.Save() # <- this is the work around
excel.Application.Quit()
I have a text editor made with Python and tkinter.
This is my 'open file' method:
def onOpen(self):
file = askopenfile(filetypes=[("Text files", "*.txt")])
txt = file.read()
self.text.delete("1.0", END)
root.title(file)
self.text.insert(1.0, txt)
file.close()
I would like to set the window title equal to the file name. At the moment I'm using whatever askopenfile return as the file name, but this returns for example:
<_io.TextIOWrapper name='/Users/user/Desktop/file.txt' mode='r' encoding='UTF-8'>
This, of course, isn't very nice. I would like whatever askopenfilename would return. But if I call askopenfile and askopenfilename the user has to use the 'open file' dialog twice.
Is there any way to retrieve the file name without the second dialog?
If not, does anyone a RegEx to filter out the file name. if you're good with RegEx, the nicest file name would of course be just 'file.txt' not '/Users/user/Desktop/file.txt'. Either way it's fine, though.
You are passing the file object so you see the reference to the file object as the title, you can get the name from the file object with name = root.title(file.name).
If you want just the base name use os.path.basename:
import os
name = os.path.basename(file.name)
from tkinter import *
from tkinter import filedialog as fd
from PIL import ImageTk, Image
import os
def openfile():
filepath= fd.askopenfilename()
onlyfilename = os.path.basename(filepath)
mylabel.config(text=onlyfilename)
myscreen=Tk()
filebutton=Button(text='choose your file',command=openfile)
filebutton.grid(row=0,column=2)
mylabel = Label(myscreen, text="You chossen file path will be displayed here")
mylabel.grid(row=1,column=2)
myscreen.mainloop()