Python detect and retrieve filename of open csv file - python

I'm using VBA to save an excel worksheet as a CSV file. The macro saves it as a CSv and then opens it in excel. I have a python code that reads the file, by the user selecting it (using tkinter) to open.
Is there a way to modify my python code to detect an open csv file, so that I can skip the user select stage? I want it to return the filepath or read open csv file. This is the current version of my code, which works if the csv file is open in excel:
import numpy as np
from Tkinter import Tk
from tkFileDialog import askopenfilename
tk=Tk()
tk.withdraw()
filename = askopenfilename()
data = np.genfromtxt(filename, dtype=[('x',float),('y',float)],comments='"', delimiter=',',skip_header=1,missing_values=True)
tk.destroy()
x=data['x']
x = x[np.logical_not(np.isnan(x))]
y=data['y']
y = y[np.logical_not(np.isnan(y))]
print x
print y

Which OS? If it is Windows, take a look at Get name of active Excel workbook from Python. The code in the question itself may do what you're looking for:
import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
print(xl.ActiveWorkbook.FullName)
As mentioned in that question's answer, this only prints the path to the most recently opened file, but in your case it sounds like the macro is opening the file, so perhaps it would work? Otherwise, take a look at the actual answer - it seems very complete.

Related

Run Excel macro from different Excel file

I know there already are many questions regarding this topic, but I couldn't figure out a solution that works out for me.
I want to run an Excel macro stored in an 'xlsm' file, but I need to run it on a different Excel file ('xlsx').
Whenever I try the code below, I get an error message saying that the macro wasn't found, so I suppose the problem has to do with the pathing.
This is what I have:
import win32com.client
import os
try:
excel = win32com.client.Dispatch('Excel.Application')
excel_path = r'C:\Users\martin\Desktop\testing_excel.xlsx'
workbook = excel.Workbooks.Open(excel_path, ReadOnly=1)
excel.Application.Run("'macro_testing.xlsm'!local_macro")
workbook.Save()
excel.Quit()
print('Macro run succesfully')
except Exception as e:
print(e)
excel.Quit()
The 'xlsm' file with the macro is named 'macro_testing.xlsm', and the macro name is 'local_macro'.
Thanks in advance!
When I have to do similar, I store the macro in a command book (.xlsm) - or even .xlam that is called from the command book (which is .xlsm) and it then opens, manipulates, saves and closes .xlsx as appropriate.
If you try to run it from within an .xlsx, you'll never be able to save the code that has done the run, not exactly advisable for repetitive workflows.
So,
macro_testing.xlsm could have another sub which would be something like:
sub runExternal()
with Sheets("Sheet1").
extPath = cells(1,2)
extBook = cells(2,2)
'Declaring the path & workbook to use within the master workbook's "Sheet1"
workbooks.open(extPath & extBook) ReadOnly:False
call local_macro()
application.displayalerts = false 'Just in case there are any GUI prompts
workbooks(extBook).close saveChanges:=True
application.displayalerts = true
end sub
For anybody there who was experiencing the same problem I had, what I finally did was open the two Excel files, like this:
import os
excel_path = os.path.abspath('Excel_to_run_macro.xlsx')
if os.path.exists(excel_path):
xl = win32com.client.Dispatch('Excel.Application')
xl.Workbooks.Open(os.path.abspath('Excel_with_macro.xlsm'), ReadOnly=1)
workbook = xl.Workbooks.Open(excel_path, ReadOnly=1)
xl.Application.Run("'Excel_with_macro.xlsm'!Macro_name")
workbook.Save()
xl.Application.Quit()
del xl

How to ignore "Enable Editing" in excel after writing data using openpyxl

I am using a Excel template which have 6 tabs (All unprotected) and writing the data on each worksheet using openpyxl module.
Once the excel file is created and when tried to open the generated file, its not showing all data untill and unless I click "Enable editing" pop up.
Is there any attribute to disable in openpyxl.
This sounds like Windows has quarantined files received over a network. As this is done when the files are received, there is no way to avoid this when creating the files.
I solved this for me.
I found the answer here:
https://codereview.stackexchange.com/questions/240136/python-script-for-refreshing-and-preprocessing-data-in-excel-report-files
I only used the refresh function and it basically opened the excel file, click/refreshed, and closed/saved. You see an Excel file appear briefly on the screen. I'll insert this in a loop to go through all the files I am creating. It might take a little while to run hundreds, but much faster than open-click-save.
Here is all the code I used:
import win32com.client as win32
def refresh(directory, file_name):
xlapp = win32.DispatchEx('Excel.Application')
xlapp.DisplayAlerts = False
xlapp.Visible = True
xlbook = xlapp.Workbooks.Open(directory + '\\' + file_name)
xlbook.RefreshAll()
xlbook.Save()
xlbook.Close()
xlapp.Quit()
return()

Python Tkinter Text Widget not displaying contents from .txt file

I am currently creating a Python Tkinter program to edit and create .txt files. In doing so, I have created a file opening system using the File Dialog method and have the user selected path saved as: a file variable. I have looped through the file and added it to the text widget via the insert method. I opened a test .txt file with a 2 line content. It simply says: this is a test file. (New line) it is used for test purposes
The problem is that the text widget appears blank
My code is:
from tkinter import *
from tkinter import FileDialog
master = Tk()
#all other code like filedialog opening code is here
editarea = Text(master,height=10,width=25)
editarea.grid(column=0,row=1)
f = open(file,"r")
for x in f:
editarea.insert(END,x)
This code is run in Python 3.7
How do I make the Text widget display the contents of the .txt file and can still be edited?
Many Thanks
(For the future)
I am aware the code above is a bit vage and won't run but you hopefully get the gist of my problem :)
here is a better solution, whole file at once
with open(file, "r") as txtr:
data = txtr.read()
editarea.insert(END, data)
this here is line by line
with open(file, "r") as txtr:
data = txtr.readlines()
for x in data:
editarea.insert(END, x)
if for some strange reason it didn't work, try this:
for x in range(len(data)):
editarea.insert(END, data[x])

How can I close a sub-process with a particular title or window name ( Excel with multiple open files )?

I am writing a script where I am unable to close one of the excel files open in Windows. There are many open files in Microsoft Excel but I have not opened them as f.open() in python.
Before the script completes it has to write to same excel file and if file is open error and script breaks.
Can I close the one of the multiple MS- Excel Window with specific title like file1, file2, file3 are open in excel and I only want to close file2.xlsx
import os
file3= output.xlsx
os.close(file3)
writer = pd.ExcelWriter('Output.xlsx', engine='xlsxwriter')
I'm not sure there's a way to do it exactly with window titles, I think the better way is to use system information about what files does each process use
from psutil import Process
from os import kill
from signal import SIGQUIT
def close_one_excel(filename, subprocesses):
""" Kills the process from `subprocesses` array,
that uses the `filename` file """
for i in subprocesses:
p = Process(i.pid)
if filename in p.open_files():
kill(p.pid, SIGQUIT)

trying to write COPIED data in a text file in python

I have copied the data from a file, and I am trying to paste it to file guru99.txt, but it is not writing to the file. Below is the piece of code. Can anyone please help me, I want to paste the copied data in txt file which I have opened?
import win32api
import win32com.client
import pyautogui
shell = win32com.client.Dispatch("WScript.Shell")
win32api.Sleep(5000)
pyautogui.moveTo(17, 213) #moving cursor to a location on software to select data
win32api.Sleep(2000)
pyautogui.click() #selecting data
win32api.Sleep(2000)
pyautogui.hotkey('ctrl', 'c') #copying data
win32api.Sleep(2000)
file_text= open("guru99.txt","w+") #making new txt file to paste copied data
file_text.write(pyautogui.hotkey('ctrl', 'v')) #pasting data using write fn, which is giving error
win32api.Sleep(2000)
file_text.close()
That's a really unpythonic way of doing what you want to do. Also, note that when you use open(filename), you are not physically opening the file. You are just reading its contents to the memory. So from pyautogui's point of view, the file is not open. Hence Ctrl+V won't work.
Since you were able to copy the data into clipboard, the pasting part is simple.
Type this in command prompt:
pip install pyperclip
After you are able to execute "ctrl+c" in your script:
import pyperclip
s = pyperclip.paste()
with open('new.txt','w') as g:
g.write(s)

Categories