Opening files in a folder with Openpyxl

Viewed 1209

I am currently trying to open the files in a folder with the below:

from tkinter import filedialog
import tkinter as tk
import openpyxl
import os

root = tk.Tk()
root.withdraw()

folder = filedialog.askdirectory()

for f in os.listdir(folder):
    wb = openpyxl.load_workbook(f)
    ws = wb.active
    v = ws['A1']
    print(v.value)

After running this, I run into errors. The value for 'f' is 'filename.xlsx' but does not include the full file path so the file cannot be opened. Is there a way to add the rest of the path so that openpyxl can recognize the files? Is there anything else I should change?

1 Answers

Just found the answer using this guide

from tkinter import filedialog
import tkinter as tk
import openpyxl
import os

root = tk.Tk()
root.withdraw()

folder = filedialog.askdirectory()

for f in os.listdir(folder):
    path = os.path.join(folder,f)
    wb = openpyxl.load_workbook(path)
    ws = wb.active
    v = ws['A1']
    print(v.value)
Related