Simply opening existing excel files with the excel application already open - python

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')

Related

Python Window Scheduler File Output

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)

Issue writting to file with pyinstaller

So an update, I found my compile issue was that I needed to change my notebook to a py file and choosing save as doesn't do that. So I had to run a different script turn my notebook to a py file. And part of my exe issue was I was using the fopen command that apparently isn't useable when compiled into a exe. So I redid the code to what is above. But now I get a write error when trying to run the script. I can not find anything on write functions with os is there somewhere else I should look?
Original code:
import requests
import json
import pandas as pd
import csv
from pathlib import Path
response = requests.get('url', headers={'CERT': 'cert'}, stream=True).json()
json2 = json.dumps(response)
f = open('data.json', 'r+')
f.write(json2)
f.close()
Path altered code:
import requests
import json
import pandas as pd
import csv
from pathlib import Path
response = requests.get('url', headers={'CERT': 'cert'}, stream=True).json()
json2 = json.dumps(response)
filename = 'data.json'
if '_MEIPASS2' in os.environ:
filename = os.path.join(os.environ['_MEIPASS2'], filename)
fd = open(filename, 'r+')
fd.write(json2)
fd.close()
The changes to the code allowed me to get past the fopen issue but created a write issue. Any ideas?
If you want to write to a file, you have to open it as writable.
fd = open(filename, 'wb')
Although I don't know why you're opening it in binary if you're writing text.

Mutagen: Importing Artwork From URL

I just started coding Python a few days ago. I'm still a noob but I'm familiar with other languages so I'm learning quick. I need help with this script I'm writing. I'm using Mutagen to tag m4a files but I'm having issues with saving artwork from a url.
(Python Version 3.7.4)
Mutagen Api: https://mutagen.readthedocs.io/en/latest/api/mp4.html
Below is code that works but it only works for local images. I need to be able to do the same thing but with an image from a url: https://is1-ssl.mzstatic.com/image/thumb/Music123/v4/e3/4a/e6/e34ae621-5922-140d-7db0-f6ce0b44d626/19UMGIM78396.rgb.jpg/1400x1400bb.jpg.
from mutagen.mp4 import MP4, MP4Cover
from time import sleep
from os import listdir, getcwd
import datetime
import requests
import urllib.request
.....MORECODE HERE......
with open('artwork.jpg', "rb") as f:
currentfile["covr"] = [
MP4Cover(f.read(), imageformat=MP4Cover.FORMAT_JPEG)
]
Now below is the code I have right now but Python keeps crashing every time I run it. I tried a couple different methods but I can't seem to figure it out. It has to be fairly simple for someone experienced with Python. I tried this already (didn't work) Python Mutagen: add cover photo/album art by url?. I think it might be for an older version of Python. Any ideas?
from mutagen.mp4 import MP4, MP4Cover
from time import sleep
from os import listdir, getcwd
import datetime
import requests
import urllib.request
.....MORE CODE HERE.....
fd = urllib.request.urlopen("https://is1-ssl.mzstatic.com/image/thumb/Music123/v4/e3/4a/e6/e34ae621-5922-140d-7db0-f6ce0b44d626/19UMGIM78396.rgb.jpg/1400x1400bb.jpg")
with open(fd, "rb") as f:
currentfile["covr"] = [
MP4Cover(f.read(), imageformat=MP4Cover.FORMAT_JPEG)
]
File "mutagen.py", line 11, in with open(fd, "rb") as f:
TypeError: expected str, bytes or os.PathLike object, not HTTPResponse
You might consider something as follows:
url_artwork="https://is1-ssl.mzstatic.com/image/thumb/Music123/v4/e3/4a/e6/e34ae621-5922-140d-7db0-f6ce0b44d626/19UMGIM78396.rgb.jpg/1400x1400bb.jpg"
urllib.request.urlretrieve(url_artwork,"local.jpg")
with open("local.jpg", "rb") as f:
currentfile["covr"] = [
MP4Cover(f.read(), imageformat=MP4Cover.FORMAT_JPEG)
]

Download dataset Which is a Zip file Contaning lots of csv file in notebook for data analysis

I am doing a data science project.
I am using google notebook for my job
My dataset is residing at here which I want to access directly at python Notebook.
I am using following line of code to get out of it.
df = pd.read_csv('link')
But Command line is throwing an error like below
What should I do?
Its difficult to answer exactly as there lack of data but here you go for this kind of request..
you have to import ZipFile & urlopen in order to get data from url and extract the data from Zip and the use the csv file for pandas processings.
from zipfile import ZipFile
from urllib.request import urlopen
import pandas as pd
import os
URL = 'https://he-s3.s3.amazonaws.com/media/hackathon/hdfc-bank-ml-hiring-challenge/application-scorecard-for-customers/05d2b4ea-c-Dataset.zip'
# open and save the zip file onto computer
url = urlopen(URL)
output = open('05d2b4ea-c-Dataset.zip', 'wb') # note the flag: "wb"
output.write(url.read())
output.close()
# read the zip file as a pandas dataframe
df = pd.read_csv('05d2b4ea-c-Dataset.zip') zip files
# if keeping on disk the zip file is not wanted, then:
os.remove(zipName) # remove the copy of the zipfile on disk
Use urllib module to download into memory the zip file which returns a file-like object that you can read(), pass it to ZipFile(standard package).
Since here there are multiple files like
['test_data/AggregateData_Test.csv', 'test_data/TransactionData_Test.csv', 'train_data/AggregateData_Train.csv', 'train_data/Column_Descriptions.xlsx', 'train_data/sample_submission.csv', 'train_data/TransactionData_Train.csv']
Load it to a dict of dataframes with filename as the key. Altogether the code will be.
from urllib.request import urlopen
from zipfile import ZipFile
from io import BytesIO
zip_in_memory = urlopen("https://he-s3.s3.amazonaws.com/media/hackathon/hdfc-bank-ml-hiring-challenge/application-scorecard-for-customers/05d2b4ea-c-Dataset.zip").read()
z = ZipFile(BytesIO(zip_in_memory))
dict_of_dfs = {file.filename: pd.read_csv(z.open(file.filename))\
for file in z.infolist()\
if file.filename.endswith('.csv')}
Now you can access dataframes of each csv like dict_of_dfs['test_data/AggregateData_Test.csv'].
Ofcourse all of this is unnecessary if you will just download the zip from the link and pass it as a zipfile.

Connecting from Python to Excel 2016(365) and perform tasks

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()

Categories