Python Writing .csv file [duplicate] - python

I can't save the active file I'm working in when I'm in openpyxl.
wb_obj = load_workbook(filename="C:\\Users\\timde\PycharmProjects\\starshipit\\test.xlsx", read_only=False)
sheet_obj = wb_obj.active
sheet_obj.cell(row=2, column=10).value = 500
wb_obj.save("test.xlsx")
I get this error back
File "C:/Users/timde/PycharmProjects/starshipit/writeback_to_sheet.py", line 22, in <module>
write_back()
File "C:/Users/timde/PycharmProjects/starshipit/writeback_to_sheet.py", line 15, in write_back
wb_obj.save("test.xlsx")
File "C:\Users\timde\PycharmProjects\starshipit\venv\lib\site-packages\openpyxl\workbook\workbook.py", line 392, in save
save_workbook(self, filename)
File "C:\Users\timde\PycharmProjects\starshipit\venv\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
File "C:\Users\timde\AppData\Local\Programs\Python\Python38-32\lib\zipfile.py", line 1251, in __init__
self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'test.xlsx'
But if I change the file name to test1.xlsx It creates a new file and saves it for me.
So the issue is only saving the current workbook I am in as itself
Thank you all in advance. Much appreciated

MS Office applications generally write-lock the files that they open. Since you have your workbook open in Excel, Python will not be able to open the same workbook. This manifests itself as the PermissionError that you are seeing. The simple solution is to close the file in Excel when you want to use it elsewhere.

Related

Python openpyxl telling me " No such file or directory:" even though python file is in same directory as the excel file, among others

Beginner here.
I've tried making new excel files, running the python code while the excel file is open, tried renaming the excel file, but nothing works. I was just following this youtube tutorial: https://www.youtube.com/watch?v=7YS6YDQKFh0&t=14s
from openpyxl import Workbook, load_workbook
workbook = load_workbook("Test2.xlsx")
The error:
Traceback (most recent call last):
File "c:\Users\Name\Desktop\Python Projects\Excel Manipulation\Excel_Test.py", line 3, in <module>
workbook = load_workbook("Test2.xlsx")
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
reader = ExcelReader(filename, read_only, keep_vba,
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 96, in _validate_archive
archive = ZipFile(filename, 'r')
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\zipfile.py", line 1239, in __init__
self.fp = io.open(file, filemode)
**FileNotFoundError: [Errno 2] No such file or directory: 'Test2.xlsx'
PS C:\Users\Name>**
I found a solution. Turns out you just need to copy the file location, convert it to raw string, and add \ExcelFile to the end:
from openpyxl import Workbook, load_workbook
location = r'C:\Users\Name\Desktop\Python Projects\Excel Manipulation\Test2.xlsx'
workbook = load_workbook(location)
Derp.

Why can't I edit my .xlsx file with openpyxl?

I am encountering a problem when running with openpyxl the code below
import openpyxl
import os
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
sheet["A1"].value
sheet["A1"].value == None
sheet["A1"].value = 42
sheet["A3"].value = 'Hello'
os.chdir("/Users/mac/Desktop")
wb.save('exceeeel.xlsx')
The error is
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/openpyxl/reader/excel.py", line 312, in load_wo
rkbook
reader = ExcelReader(filename, read_only, keep_vba,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/openpyxl/reader/excel.py", line 124, in __init_
_
self.archive = _validate_archive(fn)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/openpyxl/reader/excel.py", line 96, in _validat
e_archive
What am I doing wrong? I am using the current version of the openpyxl library.
I can't provide a confident answer because the question only includes a partial traceback. That being said, it looks like the traceback one would get for a FileNotFoundError:
C:\Python37\python.exe C:/Users/user/PycharmProjects/scratch/scratch2.py
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/scratch/scratch2.py", line 3, in <module>
wb = openpyxl.load_workbook('example.xlsx')
File "C:\Python37\lib\site-packages\openpyxl\reader\excel.py", line 313, in load_workbook
data_only, keep_links)
File "C:\Python37\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "C:\Python37\lib\site-packages\openpyxl\reader\excel.py", line 96, in _validate_archive
archive = ZipFile(filename, 'r')
File "C:\Python37\lib\zipfile.py", line 1207, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'example.xlsx'
Process finished with exit code 1
This error will be raised when the path your provided to the file you want to load with openpyxl.load_workbook does not contain the specified file. Since the only argument you provided in your call of that function is 'example.xlsx' that probably means there is no file in the folder you are running this script from.
If this 'example.xlsx' file is in a different folder then you'll want to either specify the relative path to that file as your argument or move the file into the same folder as your script.
If this isn't what's going on then you'll need to provide the full traceback that you are seeing on your end in order to get a better answer.

How to close a process (file) if it was opened by an external program, using Python?

I am writing to a file from python, if the file is open in some process, python throws error.
To make it clear, I am writing to a excel file, I want it closed if already open.
This is below code I use to write to file -
writer = pd.ExcelWriter('file_Output.xlsx', engine='xlsxwriter')
file.to_excel(writer,index=False, sheet_name='Sheet1')
Which throws below error if the file - file_Output.xlsx is already open in excel.
Traceback (most recent call last):
File "pythonclose.py", line 311, in <module>
writer.save()
File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\excel.py", line 1952, in save
return self.book.close()
File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\site-packages\xlsxwriter\workbook.py", line 306, in close
self._store_workbook()
File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\site-packages\xlsxwriter\workbook.py", line 655, in _store_workbook
allowZip64=self.allow_zip64)
File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\zipfile.py", line 1082, in __init__
self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'file_Output.xlsx'
If a file is open by an external program(such as MS Excel in this case), the file handle or control of the file is with the program. Python has no control over the file and cannot close/edit it. However, if you have the Process ID for the file, it is possible to kill the process by different means(for eg. using taskkill in Windows or even with Python).

PermissionError: [Errno 13] Permission denied: when trying to write workbook to desktop

My code is below:
from openpyxl import *
wb = Workbook()
ws = wb.active
ws.title = "primes"
prime_list = find_primes_to(1000)
index = 0
while index < prime_list.__len__():
ws.cell( row = index + 1, column = 1, value = prime_list[index])
index += 1
print("almost done")
wb.close()
wb.save('C:/Users/David/Desktop')
print("done")
Everything up to the "wb.save()" seems to be working properly, and if I run it without the path it executes just fine (though I can't find where it saves to). Adding the path throws this as an output:
almost done
Traceback (most recent call last):
File "C:/Users/David/PycharmProjects/Primes/Primes runner.py", line 62, in <module>
wb.save('C:/Users/David/Desktop')
File "C:\Users\David\PycharmProjects\Primes\venv\lib\site-packages\openpyxl\workbook\workbook.py", line 372, in save
save_workbook(self, filename)
File "C:\Users\David\PycharmProjects\Primes\venv\lib\site-packages\openpyxl\writer\excel.py", line 282, in save_workbook
archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
File "C:\Users\David\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1090, in __init__
self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'C:/Users/David/Desktop'
Process finished with exit code 1
I've checked the error code. I've tried running it as admin, I've tried running saving it to different file locations. I've tried saving it to different drives, even external flash drives. I cann't figure out how to get the proper permissions. Any suggestions?
EDIT: Alright I solved it. In order to save it you have to add add an actual file name to the end of the path like so: 'C:/Users/David/Desktop/test.xlsx'.
This will create the new file
I had the same error....but looks like i had the output file open in the background.I closed it and the program worked fine.
You need to write to a FILE. For example:
wb.close()
wb.save('C:/Users/David/Desktop/Hello.xlsx')
or
wb.save(r'C:\Users\David\Desktop\Hello.xlsx')
This will also occur when you attempt to write to an excel file while that file is currently open.

Error while loading excel file with Openpyxl

I am trying yo load an excel file using Openpyxl in Python.
from openpyxl import load_workbook
wb2 = load_workbook('Book1.xlsx')
print wb2.get_sheet_names()
It just these three lines. and it throws the following error:
Traceback (most recent call last):
File "C:/Python27/excel1.py", line 5, in <module>
wb2 = load_workbook('Book1.xlsx')
File "C:\Python27\Lib\site-packages\openpyxl\reader\excel.py", line 141, in load_workbook
archive = ZipFile(f, 'r', ZIP_DEFLATED)
File "C:\Python27\Lib\zipfile.py", line 793, in __init__
self._RealGetContents()
File "C:\Python27\Lib\zipfile.py", line 835, in _RealGetContents
raise BadZipfile, "File is not a zip file"
BadZipfile: File is not a zip file
This is exactly like their Documentation. https://openpyxl.readthedocs.org/en/latest/tutorial.html
Is their any better package to do this.
If this file does not exist at the desired location, try:
from openpyxl import load_workbook
from openpyxl import Workbook
# 1) create a workbook
wb = Workbook()
wb.save('my.xlsx')
del wb
# 2) build connection with the just created excel
book = load_workbook('my.xlsx')
It is an issue with the file. When we saved the file externally it was prompting this error. easy fix is to make a try catch and if the it gives the error create a new file in the same name and save on the same place. But for appending with old data wont work in this case.
try:
# this statement shall raise error for Badzip file
wb_obj = openpyxl.load_workbook(filename=path)
except:
# try to create a new file and save at same path
wb_obj = openpyxl.Workbook()
wb_obj.save(path)
wb_obj = openpyxl.load_workbook(filename=path)
xlsx files are zip archives. It looks like the file you're trying to open isn't. If you think this isn't the case please submit a but with a sample file.

Categories