[PYTHON] Get all xlsx filenames in a folder in a natural sort order list and build an absolute path

Background / premise / specifications

A reminder template for creating tools for working with Excel files.

As a premise of the intended operation, the following states are assumed.

--Create a folder with an arbitrary name (folder_name in the code below) on the desktop, and run it with all the xlsx you want to handle in it.

--Get the list of all xlsx file names in the folder in natural sort order

--Up to the point where the file name list is acquired in order with the for statement and the absolute path of each file is constructed.

What is natural order?

The order when a list such as "file name + number" is arranged in a way that is nice to humans.

For example

["n5", "n1", "n10"]

If you sort the list normally,

["n1", "n10", "n5"]

But in natural order,

["n1", "n5", "n10"]

become.

Execution environment

The execution environment and the version of each library are as follows.

Get the names of all xlsx files in the folder in a natural sort order list and build the absolute path.

for_all_xlsx.py


import os
from natsort import natsorted


#Arbitrary folder name created on the desktop

folder_name = "******"


#constant
desktop_path = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") + "\\Desktop"
folder_path = os.path.join(desktop_path, folder_name)


#Get Excel file name list in natural order
files = natsorted(os.listdir(folder_path))

#Build the absolute path of each file by turning the file name list with a for statement
for filename in files:
    filepath = os.path.join(folder_path, filename)
'''Describe the content you want to process below'''
    

Recommended Posts

Get all xlsx filenames in a folder in a natural sort order list and build an absolute path
Get a list of files in a folder with python without a path
Sort list elements in a specified order in Python
Recursively get the Excel list in a specific folder with python and write it to Excel.
Get 1000 posts in Python order from all Slack channels and put them together in a txt file
I want to sort a list in the order of other lists