Python Forum
How to access all xlsx files in all subdirectories?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to access all xlsx files in all subdirectories?
#1
Hello,
How to modify this program if I have more dirs in dir1 to get all xlsx.?
So the xls files are within different dirs in dir1, like
dir1\1990\1.xlsx
dir1\1991\123.xlsx
dir1\1992\124.xlsx

    import glob
    from win32com.client import Dispatch
    
    
    for file in glob.glob('C:\Users\igyulavics\Desktop\dir1\*.xlsx'):
        xl = Dispatch('Excel.Application')
        wb = xl.Workbooks.Add(file)
        wb.SaveAs(file[:-1], FileFormat=56)
        xl.Quit()
Reply
#2
glob.glob(r'C:\Users\igyulavics\Desktop\*.xlsx', recursive=True)
use recursive=True in glob

Note that you need to pass raw string if using backslash or escape the backslash or use forward slash in path
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
With pathlib you get a better abstraction.

from pathlib import Path

document_dir = Path(r'C:\Users\igyulavics\Desktop\dir1')
for xlsx_file in document_dir.glob('**/*.xlsx'):
    # xlsx_file is a Path object
    # if you use old libraries, you have to use str(xlsx_file) to convert the Path to a str
    print(xlsx_file)
This code finds all .xlsx files recursive. This should work also on Windows.
Look here: https://docs.python.org/3/library/pathli....Path.glob
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  .py pandas matplotlib .xlsx files QubeStory 1 787 Mar-23-2023, 09:38 AM
Last Post: buran
  comparison of two xlsx files Jlyk 4 1,951 Sep-20-2021, 07:13 AM
Last Post: Jlyk
  Extracting information from .xlsx files hobbyist 0 1,593 Jan-06-2021, 07:20 PM
Last Post: hobbyist
  How to loop in python over subdirectories and copy the output to other subdirectories arielma 1 1,813 Oct-22-2020, 03:38 PM
Last Post: bowlofred
  Moving Files From Subdirectories To Another Directory Harshil 5 3,986 Oct-06-2020, 10:52 AM
Last Post: ndc85430
  Creating Excel files compatible with microsoft access vkallavi 0 1,585 Sep-17-2020, 06:57 PM
Last Post: vkallavi
  How to access files from shared folder? samandhare 4 41,611 Jun-25-2020, 11:14 AM
Last Post: samandhare
  How can I speed up my openpyxl program reading Excel .xlsx files? deac33 0 3,392 May-04-2020, 08:02 PM
Last Post: deac33
  Making .exe file that requires access to text and html files ClassicalSoul 0 1,578 Apr-23-2020, 05:03 PM
Last Post: ClassicalSoul
  Random access binary files with mmap - drastically slows with big files danart 1 3,941 Jun-17-2019, 10:45 AM
Last Post: danart

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020