trying to write COPIED data in a text file in python - 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)

Related

Question about error when saving xlsm file using xlwings

I want to open an xlsm file via xlwings and then edit it and save it. However, some problems arose.
If I run the code with no excel file working, or just open another excel file and do not edit the excel file, it works fine. However, if I open an Excel file and do some work, for example open a blank Excel file and enter 'test' in cell A1, and run the code, sometimes it works, but sometimes it becomes unresponsive in the third line.(wb_xl = xw.Book(copy)) In this case, the code does not jump from the third line in an unresponsive state. What makes more sense is that the code works fine in some cases.
I want to know when the code works fine in all cases.
And there is one more problem.
If this code is executed while working with another Excel, only wb_xl should be terminated. I don't want another Excel to be closed. I want to exit only wb_xl. However, when the app.quit() code is executed, all open Excels are closed. In this case, how can I close only the Excel(wb_xl) opened through the code without closing the working Excel?
import xlwings as xw
copy = 'C:/Users/ijung/Desktop/210919_Mk_Lot_test/210922_101test.xlsm'
wb_xl = xw.Book(copy) #sometimes no response in this line
ws_xl = wb_xl.sheets['Main']
app = xw.apps.active
ws_xl.range('A1').value = 'test'
wb_xl.save()
app.quit()
#wb_xl.app.kill()
#wb_xl.close()
I also used openpyxl. However, in this part of wb_open.save(copy), an error such as xml.etree.ElementTree.ParseError: mismatched tag: line 20, column 8 occurred. When I use xlsx, the save works fine, but when I use xlsm, an error occurs.
import openpyxl
wb_open = openpyxl.load_workbook(copy, read_only = False, keep_vba = True)
ws_open = wb_open.active
ws_open.cell(1,1).value = 'test'
wb_open.save(copy) #error
wb_open.close()
As a result, the purpose of this code is to open the xlsm file by executing this code even when working with another Excel, edit and save, and close only this xlsm file.However, using multiple packages and searching multiple sites could not solve the problem.I'm under a lot of stress with this issue. Any help would be greatly appreciated. Please help me.
Thanks in advance.
openpyxl does not works with xlsm files that contains form objects
I think the problem is in app.quit() you are closing the excel instance, just use wb_xl.close()
import xlwings as xw
copy = 'C:/Users/ijung/Desktop/210919_Mk_Lot_test/210922_101test.xlsm'
wb_xl = xw.Book(copy) #sometimes no response in this line
ws_xl = wb_xl.sheets['Main']
#app = xw.apps.active # don't needed
ws_xl.range('A1').value = 'test'
wb_xl.save()
wb_xl.close()
This should only close the book, take a look this post has insteresting answers

Get text from any file type using Python

I have a file which is not .txt extension, but I can right click and open it using notepad, and it's a readable file.
However, if I try to open the file I cannot retrieve the text, or edit it.
Here's some code to make things clearer:
path=r"C:\Users\Alon\Desktop\RUN Low.spe"
f=open(path,'r+')
f.readlines()
Output:
[]
Again, if I try to open this file using Notepad - no problems. I can read and edit the text, but I wanna do it via Python. Is there a solution to this?

Can anyone help me figure out how to import this .txt file into my code?

I'm working in VS on a repository in Github. I'm importing this stats.csv file into my code but the .readlines() call isn't printing anything. Does anyone know why? Thank you
Tried many different import methods
#this is our main code
import os
cmd = 'curl https://raw.githubusercontent.com/ksu-is/NFLQuarterbackstatIdentifier/master/stats.csv -o stats.txt'
os.system(cmd)
stats = open('stats.txt', 'a+')
statheadings = stats.readlines()
print(statheadings)
print("123123")
Should print the stats.csv file lines
I tried your code, and it worked well without 'a+' option when open the text file.
Your code shows nothing because you opened file as a 'wrting' mode.
You should give the option as 'r' or 'r+' or just leave it as default.
'r' : open for reading (default)
'a' : open for writing, appending to the end of the file if it exists.
'+' : open a disk file for updating (reading and writing)
Try:
stats = open('stats.txt') # select
#stats = open('stats.txt','r') # one of
#stats = open('stats.txt','r+') # these
statheadings = stats.readlines()
print(statheadings)
It will work as well, and the result: ['404: Not Found\n']
If you want to check only a value, you can add index also.
Print only the last line:
print(satheadings[-1])
Result:
404: Not Found
Rather than attempting to save the file to the disk first, you can just open it directly:
import requests
response = requests.get('https://raw.githubusercontent.com/ksu-is/NFLQuarterbackstatIdentifier/master/stats.csv')
print(response.text)
However, the URL that you're trying to access is giving me a 404. Is this because it's in a private repository? If so, you'll want to store it somewhere where it's publicly accessible so your program can reach it (or otherwise set up a more complicated authentication scheme).

How to open a .data file extension

I am working on side stuff where the data provided is in a .data file. How do I open a .data file to see what the data looks like and also how do I read from a .data file programmatically through python? I have Mac OSX
NOTE: The Data I am working with is for one of the KDD cup challenges
Kindly try using Notepad or Gedit to check delimiters in the file (.data files are text files too). After you have confirmed this, then you can use the read_csv method in the Pandas library in python.
import pandas as pd
file_path = "~/AI/datasets/wine/wine.data"
# above .data file is comma delimited
wine_data = pd.read_csv(file_path, delimiter=",")
It vastly depends on what is in it. It could be a binary file or it could be a text file.
If it is a text file then you can open it in the same way you open any file (f=open(filename,"r"))
If it is a binary file you can just add a "b" to the open command (open(filename,"rb")). There is an example here:
Reading binary file in Python and looping over each byte
Depending on the type of data in there, you might want to try passing it through a csv reader (csv python module) or an xml parsing library (an example of which is lxml)
After further into from above and looking at the page the format is:
Data Format
The datasets use a format similar as that of the text export format from relational databases:
One header lines with the variables names
One line per instance
Separator tabulation between the values
There are missing values (consecutive tabulations)
Therefore see this answer:
parsing a tab-separated file in Python
I would advise trying to process one line at a time rather than loading the whole file, but if you have the ram why not...
I suspect it doesnt open in sublime because the file is huge, but that is just a guess.
To get a quick overview of what the file may content you could do this within a terminal, using strings or cat, for example:
$ strings file.data
or
$ cat -v file.data
In case you forget to pass the -v option to cat and if is a binary file you could mess your terminal and therefore need to reset it:
$ reset
I was just dealing with this issue myself so I thought I would share my answer. I have a .data file and was unable to open it by simply right clicking it. MACOS recommended I open it using Xcode so I tried it but it did not work.
Next I tried open it using a program named "Brackets". It is a text editing program primarily used for HTML and CSS. Brackets did work.
I also tried PyCharm as I am a Python Programmer. Pycharm worked as well and I was also able to read from the file using the following lines of code:
inf = open("processed-1.cleveland.data", "r")
lines = inf.readlines()
for line in lines:
print(line, end="")
It works for me.
import pandas as pd
# define your file path here
your_data = pd.read_csv(file_path, sep=',')
your_data.head()
I mean that just take it as a csv file if it is seprated with ','.
solution from #mustious.

Python detect and retrieve filename of open csv file

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.

Categories