Try:
sheet_names = []
for x in files:
sheet_names.append(openpyxl.load_workbook(x).sheetnames)
Or, using a list comprehension
:
sheet_names = [openpyxl.load_workbook(x).sheetnames for x in files]
Update:
If you encounter an error message like:
BadZipFile: File is not a zip file
This probably means that the file you are trying to access is corrupted. I.e. openpyxl
is simply unable to open the file, and the remedy to this situation, i.e. fixing the file, I mean, lies outside the code; you will have to take a closer look at that particular file.
However, you can use try ... except
to avoid having such an event interrupt the rest of your procedure. E.g.:
sheet_names = []
for x in files:
try:
sheet_names.append(openpyxl.load_workbook(x).sheetnames)
except Exception as e:
print(f'Unable to process {x}. Error raised', end=' ')
print(e)
E.g. whenever the code encounters a BadZipFile
, now you'll see a print: Unable to process {path_to/some_file.xlsx}. Error raised File is not a zip file
.
Explanation error
The error occurs because you are referencing files
(i.e. a list
), rather than the items inside the list (i.e. x
) in this line:
openpyxl.load_workbook(files) # we need `x` here instead of `files`
Next, in order to actually use the result from the function call, you should have assigned it to a variable, e.g. wb = openpyxl.load_workbook(x)
and then pass it to the list.append
function. I.e.:
sheet_names.append(files.sheetnames) # we would need `wb.sheetnames` here
However, as shown above, you can just put all of this is a one-liner (so, skipping the intermediate assignment to wb
).