Cant save an excel file using python script - python

def getFile():
global filename, path, path2
filename = QtWidgets.QFileDialog.getOpenFileName()[0]
path = filename
print(path)
I think the problem is in this function
def getTo():
wb = load_workbook(filename = filename)
and there is mising some settings in filename functon,
i tried using unicode, but it doesnt solve the problem
Traceback (most recent call last):
File "C:/Users/pro10/PycharmProjects/Program/gui5.py", line 118, in getTo
sheet['A' + str(rows)] = text1
File "C:\Users\pro10\PycharmProjects\pythonProject\venv\lib\site-packages\openpyxl\worksheet\worksheet.py", line 313, in __setitem__
self[key].value = value
File "C:\Users\pro10\PycharmProjects\pythonProject\venv\lib\site-packages\openpyxl\cell\cell.py", line 216, in value
self._bind_value(value)
File "C:\Users\pro10\PycharmProjects\pythonProject\venv\lib\site-packages\openpyxl\cell\cell.py", line 199, in _bind_value
raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert <function text1 at 0x0000023DFE3D3A60> to Excel

Did you import the load_workbook function, like this?
from openpyxl import load_workbook

Related

Saving changes to workbook using openpyxl

An excel sheet export from an app adds blank columns and rows to the output data. I'm trying to remove it before massaging the data.
So I have some simple code to delete the first 3 rows and first 2 columsn, then save the changes.
When I use Workbook.save(path) I get a traceback error. I researched on stackoverflow and it looks like this simple code should be working. I've even tried just putting the filename but that also giving similar error.
I'm not sure why I'm getting this error.
Update: I corrected the typo Workbook.save(path) to workbook.save(path).
import openpyxl
import pandas as pd
from openpyxl import Workbook
# Give the location of the file
path = 'C:\\Users\\cbout\\Desktop\\2022 Data.xlsx'
filename = '2022 Data.xlsx'
DF = pd.read_excel(path, sheet_name=1)
# # To open the workbook
# # workbook object is created
workbook = openpyxl.load_workbook(path)
# # Get workbook active sheet objectmfrom the active attribute
worksheet = workbook.active
#Delete first 2 columns.
worksheet.delete_cols(0,2)
#Delete first 3 rows.
worksheet.delete_rows(0,4)
workbook.save(path)
New Traceback Error after updates
PS C:\Users\cbout\Documents\GitHub> & "C:/Program Files/Python310/python.exe" c:/Users/cbout/Documents/GitHub/Python/Stewardship.py
Traceback (most recent call last):
File "c:\Users\cbout\Documents\GitHub\Python\Stewardship.py", line 9, in <module>
stewardDF = pd.read_excel(path, sheet_name=1)
File "C:\Users\cbout\AppData\Roaming\Python\Python310\site-packages\pandas\util\_decorators.py", line 311, in wrapper
return func(*args, **kwargs)
File "C:\Users\cbout\AppData\Roaming\Python\Python310\site-packages\pandas\io\excel\_base.py", line 457, in read_excel
io = ExcelFile(io, storage_options=storage_options, engine=engine)
File "C:\Users\cbout\AppData\Roaming\Python\Python310\site-packages\pandas\io\excel\_base.py", line 1385, in __init__
engine = config.get_option(f"io.excel.{ext}.reader", silent=True)
File "C:\Users\cbout\AppData\Roaming\Python\Python310\site-packages\pandas\_config\config.py", line 256, in __call__
return self.__func__(*args, **kwds)
File "C:\Users\cbout\AppData\Roaming\Python\Python310\site-packages\pandas\_config\config.py", line 128, in _get_option
key = _get_single_key(pat, silent)
File "C:\Users\cbout\AppData\Roaming\Python\Python310\site-packages\pandas\_config\config.py", line 114, in _get_single_key
raise OptionError(f"No such keys(s): {repr(pat)}")
pandas._config.config.OptionError: No such keys(s): 'io.excel.zip.reader'

TypeError: expected <class 'openpyxl.styles.fills.Fill'>

I`m trying to download and then open excel file (report) generated by marketplace with openpyxl.
import requests
import config
import openpyxl
link = 'https://api.telegram.org/file/bot' + config.TOKEN + '/documents/file_66.xlsx'
def save_open(link):
filename = link.split('/')[-1]
r = requests.get(link)
with open(filename, 'wb') as new_file:
new_file.write(r.content)
wb = openpyxl.open ('file_66.xlsx')
ws = wb.active
cell = ws['B2'].value
print (cell)
save_open(link)
After running this code I got the above:
Traceback (most recent call last):
File "C:\Python 3.9\lib\site-packages\openpyxl\descriptors\base.py", line 55, in _convert
value = expected_type(value)
TypeError: Fill() takes no arguments
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Home\Documents\myPython\bot_WB\main.py", line 20, in <module>
save_open(link)
File "C:\Users\Home\Documents\myPython\bot_WB\main.py", line 14, in save_open
wb = openpyxl.open ('file_66.xlsx')
File "C:\Python 3.9\lib\site-packages\openpyxl\reader\excel.py", line 317, in load_workbook
reader.read()
File "C:\Python 3.9\lib\site-packages\openpyxl\reader\excel.py", line 281, in read
apply_stylesheet(self.archive, self.wb)
File "C:\Python 3.9\lib\site-packages\openpyxl\styles\stylesheet.py", line 198, in apply_stylesheet
stylesheet = Stylesheet.from_tree(node)
File "C:\Python 3.9\lib\site-packages\openpyxl\styles\stylesheet.py", line 103, in from_tree
return super(Stylesheet, cls).from_tree(node)
File "C:\Python 3.9\lib\site-packages\openpyxl\descriptors\serialisable.py", line 103, in from_tree
return cls(**attrib)
File "C:\Python 3.9\lib\site-packages\openpyxl\styles\stylesheet.py", line 74, in __init__
self.fills = fills
File "C:\Python 3.9\lib\site-packages\openpyxl\descriptors\sequence.py", line 26, in __set__
seq = [_convert(self.expected_type, value) for value in seq]
File "C:\Python 3.9\lib\site-packages\openpyxl\descriptors\sequence.py", line 26, in <listcomp>
seq = [_convert(self.expected_type, value) for value in seq]
File "C:\Python 3.9\lib\site-packages\openpyxl\descriptors\base.py", line 57, in _convert
raise TypeError('expected ' + str(expected_type))
TypeError: expected <class 'openpyxl.styles.fills.Fill'>
[Finished in 1.6s]
If you run file properties/details you can see that this file was generated by "Go Exelize" (author: xuri). To run this file you need to separate code in two parts. First: download file. Then you need to manually open it with MS Excel, save file and close it (after this "Go Excelize" switch to "Microsoft Excel"). And only after that you can run the second part of the code correctly with no errors. Can anyone help me to handle this problem?
I had the same problem, "TypeError('expected ' + str(expected_type))", using pandas.read_excel, which uses openpyxl. If I open the file, save and close it, it will work with both, pandas and openpyxl.
Upon further attempts I could open the file using the "read_only=True" in openpyxl, but while iterating over the rows I would still get the error, but only when all the rows ended, in the end of the file.
I belive it could be something in the EOF (end of file) and openpyxl don't have ways of treating it.
Here is the code that I used to test and worked for me:
import openpyxl
wb = openpyxl.load_workbook(my_file_name, read_only=True)
ws = wb.worksheets[0]
lis = []
try:
for row in ws.iter_rows():
lis.append([cell.value for cell in row])
except TypeError:
print('Skip error in EOF')
Used openpyxl==3.0.10

Converting a dataframe into a config file

def load_config_report(config_file_path):
config = configparser.ConfigParser()
pharmacy_settings = pd.read_excel(config_file_path,
sheet_name='pharmacy_settings')
for each in pharmacy_settings['facility_name']:
config[each]['facility_alias'] = pharmacy_settings['facility_alias']
config[each]['facility_group_id'] = pharmacy_settings['facility_group_id']
config[each]['invoice_num'] = pharmacy_settings['invoice_num']
with open('X:\\Reports\\Invoices\\config.ini', 'w') as configfile:
config.write(configfile)
Trying to convert the contents of an excel file into a .ini file. First column is the [section], remaining columns are variables in that section. Currently getting a KeyError due to how I'm iterating/slicing the dataframe. Is this a good approach to achieve this?
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.752.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "X:\Python Dev\REFACTOR\invoicerefactor.py", line 41, in read_config
options.load_config_report(config_file_path.get())
File "X:\Python Dev\REFACTOR\options.py", line 10, in load_config_report
config[each]['facility_alias'] = pharmacy_settings['facility_alias']
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.752.0_x64__qbz5n2kfra8p0\lib\configparser.py", line 960, in __getitem__
raise KeyError(key)
KeyError: 'ALL CARE HEALTH SOLUTIONS'
You need to initialize an empty dictionary for config[each] before completing the data.
for each in pharmacy_settings['facility_name']:
config[each] = {}
config[each]['facility_alias'] = pharmacy_settings['facility_alias']
#...
That's how the examples in the docs are doing it.

Python Screen capture

I'm trying to write a program to take screen cap using a global hot key. Below is the corresponding code:
from datetime import datetime
import os
from pynput import keyboard
import pyautogui
import pathlib
def on_activate():
today = datetime.now()
d = today.strftime("%Y-%m-%d-%H-%M-%S")
myScreenshot = pyautogui.screenshot(region=(200,200, 1720, 800))
time_stamp = '{:%y%d%m}'.format(today)
fpath = pathlib.Path("C:","Users","Desktop","TestScreenCap", time_stamp)
if not os.path.exists(fpath):
os.makedirs(fpath)
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<ctrl>+<alt>+h'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()
Error Message:
Unhandled exception in listener callback
Traceback (most recent call last):
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2138, in save format = EXTENSION[ext]
KeyError: ''
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 211, in inner
return f(self, *args, **kwargs)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process self.on_press(key)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 127, in inner
if f(*args) is False:
File "C:/Users/PycharmProjects/untitled1/123.py", line 18, in <lambda>
return lambda k: f(l.canonical(k))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\__init__.py", line 182, in press
self._on_activate()
File "C:/Users/PycharmProjects/untitled1/123.py", line 15, in on_activate
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2140, in save
raise ValueError("unknown file extension: {}".format(ext)) from e
ValueError: unknown file extension:
Traceback (most recent call last):
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2138, in save
format = EXTENSION[ext]
KeyError: ''
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/Users/PycharmProjects/untitled1/123.py", line 26, in <module>
l.join()
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 259, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\six.py", line 702, in reraise
raise value.with_traceback(tb)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 211, in inner
return f(self, *args, **kwargs)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process
self.on_press(key)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 127, in inner
if f(*args) is False:
File "C:/Users/PycharmProjects/untitled1/123.py", line 18, in <lambda>
return lambda k: f(l.canonical(k))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\__init__.py", line 182, in press
self._on_activate()
File "C:/Users/PycharmProjects/untitled1/123.py", line 15, in on_activate
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2140, in save
raise ValueError("unknown file extension: {}".format(ext)) from e
ValueError: unknown file extension:
I do not know how to save the image to the folder. I expect the code below will not work this:
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
Changing the function to on_activate with a simple action such as:
Print("Hello")
The hotkey script works perfectly.
I am new to programming, so any help is appreciated!
Here the fixed code:
from datetime import datetime
import os
from pynput import keyboard
import pyautogui
import pathlib
def on_activate():
today = datetime.now()
d = today.strftime("%Y-%m-%d-%H-%M-%S")
myScreenshot = pyautogui.screenshot(region=(200,200, 1720, 800))
time_stamp = '{:%y%d%m}'.format(today)
fpath = pathlib.Path("C:\\","Users","Desktop","TestScreenCap", time_stamp)
if not os.path.exists(fpath):
os.makedirs(fpath)
myScreenshot.save(pathlib.Path(fpath,d + ".jpg"))
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<ctrl>+<alt>+h'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()
The problem was that you were using:
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
The function pathlib.Path(fpath,d,".jpg") join the string adding the \ to the end of each, so the path where you are trying to save the file is:
C:Users\Desktop\TestScreenCap\200309\2020-09-03-16-50-20\.jpg
As you can see the filename is the extension, that throw the exception.
Just replace with this: myScreenshot.save(pathlib.Path(fpath,d + ".jpg"))
Another problem on the specified path is that C: is interpreted as Drive, so when you save the function, is saved to the path where your program is currently running, not at the real specified path. To fix this part, just replace C: with C:\\.
Reading your code I think you would like to save the screenshot in the current user Desktop, if so replace the line: fpath = pathlib.Path("C:\\","Users","Desktop","TestScreenCap", time_stamp) with fpath = pathlib.Path(os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop'), time_stamp) and just add on the top the import os. With this you don't need to care about the right generation for the path.

How to replace a text/string in a file with another text/string using python 2.7

I have written the below code to replace the string "YANTRAPRODPATH" with "YantraProd1" in a file and save it:-
fileToModify = open("C:/workspace/PROD/bat1/customer_overrides.properties",'r+')
textToSearch = "<YANTRAPRODPATH>"
textToReplace = "YantraProd1"
f = fileinput.FileInput(fileToModify, inplace=True, backup='.bak')
for line in f:
print(line.replace(textToSearch, textToReplace))
f.close()
But I am getting below error:-
C:\workspace>python c:/workspace/ReplaceText.py
Traceback (most recent call last):
File "c:/workspace/ReplaceText.py", line 20, in <module>
for line in f:
File "C:\Python27\lib\fileinput.py", line 237, in next
line = self._readline()
File "C:\Python27\lib\fileinput.py", line 316, in _readline
os.rename(self._filename, self._backupfilename)
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect
Am I missing something here? And is there a more simpler way to do this?
FileInput constructor expects filename or list of filenames and not file object.
fileToModify = "C:/workspace/PROD/bat1/customer_overrides.properties"
textToSearch = "<YANTRAPRODPATH>"
textToReplace = "YantraProd1"
f = fileinput.FileInput(fileToModify, inplace=True, backup='.bak')
for line in f:
print(line.replace(textToSearch, textToReplace))
f.close()

Categories

Resources