Python listdir sort by name

How to sort all files in a folder in Python

Python os module provides us listdir function to list all files in a directory or folder. We need to pass the directory path to this function and it returns us the name of all entries in that folder. This function is defined as below :

The returned list of the files is in arbitary order. It also doesn’t include any special entries . and .. even if it is included. The path parameter is optional starting from python 3.2. If you don’t pass the path, it will return all entries in the current folder.

Читайте также:  Css hidden and no space

For this example, I have created one folder with three files :

I have also created one file example.py with the below code :

It prints the contents of the folder including itself :

['third.mp3', 'example.py', 'first.txt', 'second.md'] 

These names are not sorted. If you want to sort the names, you need to use the sorted function with result like below :

import os print(sorted(os.listdir())) 

Execute it and it will print all files sorted by name :

['example.py', 'first.txt', 'second.md', 'third.mp3'] 

Источник

Python: Get list of files in directory sorted by name

In this article, we will discuss different ways to get list of all files in a directory / folder sorted by name in python.

Table of contents

Get list of files in directory sorted by name using glob()

In python, the glob module provides a function glob() to find files in a directory based on matching pattern. Similar to the unix path expansion rules, we can use wildcards and regular expression to match & find few or all files in a directory. We will use this to get a list of all files in a directory and then sort that list of files by name. Steps are as follows,

  1. Get a list of all files or directories in a given directory using glob().
  2. Using the filter() function and os.path.isfileIO(), select files only from the list.
  3. Sort the list of files by name using sorted() function.

Complete example to get a list of all files in directory sorted by name is as follows,

import glob import os dir_name = 'C:/Program Files/Java/jdk1.8.0_191/include/' # Get list of all files in a given directory sorted by name list_of_files = sorted( filter( os.path.isfile, glob.glob(dir_name + '*') ) ) # Iterate over sorted list of files and print the file paths # one by one. for file_path in list_of_files: print(file_path)

Frequently Asked:

C:/Program Files/Java/jdk1.8.0_191/include\classfile_constants.h C:/Program Files/Java/jdk1.8.0_191/include\jawt.h C:/Program Files/Java/jdk1.8.0_191/include\jdwpTransport.h C:/Program Files/Java/jdk1.8.0_191/include\jni.h C:/Program Files/Java/jdk1.8.0_191/include\jvmti.h C:/Program Files/Java/jdk1.8.0_191/include\jvmticmlr.h

In this solution we created a list of files in a folder using globe() function. Then passed the list to filter() function to select only files from the list and skip dictionaries etc. For this we passed the os.path.isfile() function as an argument to the filter() function. Then we passed the list of files to the sorted() function, which returned a list of files in directory sorted by name.

But the list contains the complete paths of the files. What if we want only file names sorted by names?

Get list of files in directory sorted by names using os.listdir()

In Python, the os module provides a function listdir(dir_path), which returns a list of file and sub-directory names in the given directory path. Then using the filter() function create list of files only. Then sort this list of file names based on the name using the sorted() function.

Complete example to get list of files in directory sorted by name is as follows,

import os dir_name = 'C:/Program Files/Java/jdk1.8.0_191/include/' # Get list of all files in a given directory sorted by name list_of_files = sorted( filter( lambda x: os.path.isfile(os.path.join(dir_name, x)), os.listdir(dir_name) ) ) for file_name in list_of_files: print(file_name)
classfile_constants.h jawt.h jdwpTransport.h jni.h jvmti.h jvmticmlr.h

In this solution we created a list of file names in a folder sorted by name.

Python: Get list of files in directory and sub-directories sorted by name

In both the previous examples we created a list of files in a directory sorted by name. But it covered the files in the given directory only, not in nested directories. So, if you want to get a list of all files in directory and sub-directory sorted by name, then checkout this example,

import glob import os dir_name = 'C:/Program Files/Java/jdk1.8.0_191/include/' # Get list of all files in a given directory & sub-directories sorted by name list_of_files = sorted( filter( os.path.isfile, glob.glob(dir_name + '/**/*', recursive=True) ) ) # Iterate over sorted list of files and print the file paths # one by one. for file_path in list_of_files: print(file_path)
C:/Program Files/Java/jdk1.8.0_191/include\classfile_constants.h C:/Program Files/Java/jdk1.8.0_191/include\jawt.h C:/Program Files/Java/jdk1.8.0_191/include\jdwpTransport.h C:/Program Files/Java/jdk1.8.0_191/include\jni.h C:/Program Files/Java/jdk1.8.0_191/include\jvmti.h C:/Program Files/Java/jdk1.8.0_191/include\jvmticmlr.h C:/Program Files/Java/jdk1.8.0_191/include\win32\bridge\AccessBridgeCallbacks.h C:/Program Files/Java/jdk1.8.0_191/include\win32\bridge\AccessBridgeCalls.c C:/Program Files/Java/jdk1.8.0_191/include\win32\bridge\AccessBridgeCalls.h C:/Program Files/Java/jdk1.8.0_191/include\win32\bridge\AccessBridgePackages.h C:/Program Files/Java/jdk1.8.0_191/include\win32\jawt_md.h C:/Program Files/Java/jdk1.8.0_191/include\win32\jni_md.h

We used the glob() function with pattern ‘/**/*’ and recursive=True argument. It gave a list of all files, sub- directories and files in the sub-directories. Then using the filter() function and os.path.isfile() we filtered the files only and skipped the directories. Then using the sorted() function, sorted these filtered files and created a list of files sorted by name.

We learned about different ways to get a list of files in a folder, sorted by name.

Источник

8 Examples to Implement os.listdir() in Python

8 Examples to Implement os.listdir() in Python

Hello coders!! This article will be learning about the os.listdir function in Python. The os module allows us to use the functionality dependent on the operating system in a portable manner. listdir() is a method available in the os module. It returns a list containing the contents of the directory given by path. Let us learn about this topic in detail.

What is the os.listdir() method in Python?

It is a method available in the os module of Python. This method is used to retrieve the list of files and directories present in the specified directory. In case the directory is not specified, the contents of the present working directory are returned.

  • SYNATX: os.listdir(path)
  • PARAMETERS: It is optional. It contains the path of the directory.
  • RETURN VALUE: a list containing the entries’ names in the directory given by path.

Let us see some illustrated examples to use listdir() using Python.

Example 1: To get the files and directories in root directory using listdir():

import os path = "/" dirct = os.listdir(path) print("Files and directories:") print(dirct)

Output & Explanation:

Output of listdir() to get content of root

In this example, we selected the root directory as our desired path. We then used the listdir() method to get the list of directories and files present inside the root directory.

Example 2: To get the files and directories in present working directory:

import os path = os.getcwd() dirct = os.listdir(path) print("Path:") print(path) print() print("Files and directories:") print(dirct)

Output & Explanation:

Output of listdir() to get content of present working directory

We first used the getcwd() method to get the path of the current working directory. We then passed this path as a parameter to the method to retrieve the contents of the current working directory.

Example 3: Not using the path parameter in listdir() In Python:

import os dirct = os.listdir() print("Files and directories:") print(dirct)

Output & Explanation:

Output of listdir() without passing the parameter

In this particular example, we did not pass the path parameter of the function. As a result, the function automatically took the path of the current working directory, thus returning the contents of the same.

Example 4: loop listdir in try-except using Python:

def loop(): try: for txt in os.listdir(path): if txt.endswith(txt_extension): print(path + txt) except KeyboardInterrupt: exit()

In this code, we have iterated through the directory’s contents to look for the files having ‘txt_extension’ inside the try-except block. If the file having the specified extension is received, its name and path are printed. We have used the inbuilt KeyboardInterrupt exception. This exception is raised when the user presses an interrupt key like ctrl+c.

Example 5: Python listdir sort by date:

import glob import os file = glob.glob("*.ipynb") file.sort(key=os.path.getmtime) print("\n".join(files))

Output & Explanation:

listdir sort by date

We have used the glob module, which is used to find all the pathnames matching a specified pattern. We then used the sort() method to sort the files with the extension ‘ipynb’ according to time. By default, the result is sorted by name.

Example 6: Python listdir sort by name:

import os dirct = os.listdir() print("Files and directories:") print(dirct.sort())

Output & Explanation:

Output of listdir() without passing the parameter

Here, we have used the sort() method to sort the contents of the directory as per the name. Anyway, by default, the output of os.listdir() will be sorted as per the name only.

Example 7: Python listdir absolute path:

import os absp = os.path.abspath(os.getcwd()) print("Full path: " + absp) print("Directory Path: " + os.path.dirname(absp))

Output & Explanation:

absolute path

Here, we have used the abspath() method to get the absolute path of the current directory. We then used the dirname() method to get the given absolute path’s directory path.

Example 8: Python listdir with specific extension:

import glob import os file = glob.glob("*.ipynb") file.sort(key=os.path.getmtime) print("\n".join(files))

Output & Explanation:

specific extension

As we can see, here we have extracted only the files having the extension ‘ipynb’ using the glob module.

Conclusion | Python os.listdir():

With this, we come to an end to this article. I hope it was easy to understand the concept of listdir() in python and the various ways in which it can be used to extract the contents at a given path.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Источник

Оцените статью