I have 2 folders named as Excel
and CSV
. The Excel folder contains excel files with prefix "_Updated" that I would like to convert to CSV with UTF-8 encoding, and If the file contains multiple sheets then new csv
file will be created based on sheet. However, when I run below code, I am receiving PermissionError as shown below not sure what is wrong with below code ?
Thanks in advance for your time!
Code:
from pathlib import Path
import openpyxl
from openpyxl import load_workbook
CSV_FILE_PATH='/Excel'
CSV_FILE_SAVE='/CSV'
for file in Path(CSV_FILE_PATH).glob('*_Updated.xlsx'):
wb = load_workbook(file)
print(file, wb.active.title)
for sheetname in wb.sheetnames:
with open(CSV_FILE_PATH, 'r ') as f_in, open(CSV_FILE_SAVE, 'w',encoding="utf-8") as f_out:
content = f_in.read()
spamwriter=csv.writer(f_out)
for row in wb[sheetname].rows:
spamwriter.writerow([cell.value for cell in row])
Error:
PermissionError Traceback (most recent call last)
<ipython-input-6-2ef7cc7706ca> in <module>
10 print(file, wb.active.title)
11 for sheetname in wb.sheetnames:
---> 12 with open(CSV_FILE_PATH, 'r ') as f_in, open(CSV_FILE_SAVE, 'w',encoding="utf-8") as f_out:
13 content = f_in.read()
14 spamwriter=csv.writer(f_out)
PermissionError: [Errno 13] Permission denied: '/Excel'
CodePudding user response:
You are getting a PermissionDenied
error because you are attempting to open a directory for reading as if it were a file. You will get this error on Windows if you attempt a file operation on a directory.
This is where you attempt to read in a directory, in your case, the directory /Excel
:
with open(CSV_FILE_PATH, 'r ') as f_in, ... :
f_in
is later used in the line content = f_in.read()
. However, you aren't using content
anywhere, so I suggest you get rid of it, as then you can also get rid of the open(CSV_FILE_PATH, 'r ') as f_in
part of the line above. That should sort out your problem:
with open(CSV_FILE_SAVE, 'w',encoding="utf-8") as f_out:
spamwriter=csv.writer(f_out)
for row in wb[sheetname].rows:
spamwriter.writerow([cell.value for cell in row])