Check files in dir python

Python List Files in a Directory

Also, there are multiple ways to list files in a directory. In this article, We will use the following four methods.

  • os.listdir(‘dir_path’) : Return the list of files and directories in a specified directory path.
  • os.walk(‘dir_path’) : Recursively get the list of all files in a directory and subdirectories.
  • os.scandir(‘path’) : Returns directory entries along with file attribute information.
  • glob.glob(‘pattern’) : glob module to list files and folders whose names follow a specific pattern.

Table of contents

How to List All Files in a Directory using Python

Use the listdir() and isfile() functions of an os module to list all files in a directory. Here are the steps.

  1. Import os module First, import the os module. This module helps us to work with operating system-dependent functionality in Python. The os module provides functions for interacting with the operating system.
  2. Decide the path to the directory Next, decide the path to the directory you want to list the files of. Make sure you use the correct format for your operating system. For example, on Windows, paths are typically written with backslashes (e.g., ‘C:\\path\\to\\your\\directory’ ).
  3. Use os.listdir(‘directory_path’) function Now use the os.listdir(‘directory_path’) function to get a list of the names of the entries ( the files and directories ) in the directory given by the directory_path .
  4. Iterate the result Next, Use for loop to Iterate the list returned by the os.listdir(directory_path) function. Using for loop we will iterate each entry returned by the listdir() function.
  5. Use isfile(path) function Now, In each loop iteration, use the os.path.isfile(‘path’) function to check whether the current entry is a file or a directory. If it is a file, then add it to a list. This function returns True if a given path is a file. Otherwise, it returns False.
Читайте также:  Java lang nosuchmethoderror org objectweb asm

Example: List Files in a Directory

Let’s see how to list all files in an ‘account’ directory.

Example 1: List only files in a directory

import os # directory/folder path dir_path = r'E:\account' # list to store files res = [] # Iterate directory for file_path in os.listdir(dir_path): # check if current file_path is a file if os.path.isfile(os.path.join(dir_path, file_path)): # add filename to list res.append(file_path) print(res)

Here we got three file names.

['profit.txt', 'sales.txt', 'sample.txt']
  • The os.listdir(dir_path) will list files only in the current directory and ignore the subdirectories.
  • The os.path.join(directory, file_path) is used to get the full path of the entry.

Also, you should handle the case where the directory does not exist or an error occurs while accessing it. For this, you can use a try-except block. Here’s how you can modify the code:

import os def list_files(dir_path): # list to store files res = [] try: for file_path in os.listdir(dir_path): if os.path.isfile(os.path.join(dir_path, file_path)): res.append(file_path) except FileNotFoundError: print(f"The directory does not exist") except PermissionError: print(f"Permission denied to access the directory ") except OSError as e: print(f"An OS error occurred: ") return res # directory/folder path dir_path = r'E:\account' files = list_files(dir_path) print('All Files:', files) 

Generator Expression:

If you know generator expression, you can make code smaller and simplers using a generator function as shown below.

import os def get_files(path): for file in os.listdir(path): if os.path.isfile(os.path.join(path, file)): yield file

Then simply call it whenever required.

for file in get_files(r'E:\\account\\'): print(file)

Example 2: List both files and directories.

Directly call the listdir(‘path’) function to get the content of a directory.

import os # folder path dir_path = r'E:\\account\\' # list file and directories res = os.listdir(dir_path) print(res)

As you can see in the output, ‘reports_2021’ is a directory.

['profit.txt', 'reports_2021', 'sales.txt', 'sample.txt']

os.walk() to list all files in a directory and subdirectories

Using the os.walk() function we can list all directories, subdirectories, and files in a given directory.

The os.walk() function returns a generator that creates a tuple of values (current_path, directories in current_path, files in current_path).

It is a recursive function, i.e., every time the generator is called, it will follow each directory recursively to get a list of files and directories until no further sub-directories are available from the initial directory.

For example, calling the os.walk(‘path’) will yield two lists for each directory it visits. The first list contains files, and the second list includes directories.

Let’s see the example of how to list all files in a directory and its subdirectories.

from os import walk # folder path dir_path = r'E:\\account\\' # list to store files name res = [] for (dir_path, dir_names, file_names) in walk(dir_path): res.extend(file_names) print(res)
['profit.txt', 'sales.txt', 'sample.txt', 'december_2021.txt']

Note: You can also add a break statement inside a loop to stop looking for files recursively inside subdirectories.

from os import walk # folder path dir_path = r'E:\\account\\' res = [] for (dir_path, dir_names, file_names) in walk(dir_path): res.extend(file_names) # don't look inside any subdirectory break print(res) 

os.scandir() To get the list of files in a directory

The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases.

It returns an iterator of os.DirEntry objects, which contain file names.

import os # get all files inside a specific folder dir_path = r'E:\\account\\' for path in os.scandir(dir_path): if path.is_file(): print(path.name)
profit.txt sales.txt sample.txt

Glob Module to list Files of a Directory

The Python glob module, part of the Python Standard Library, is used to find the files and folders whose names follow a specific pattern.

For example, to get all files of a directory, we will use the dire_path/*.* pattern. Here, *.* means file with any extension.

Let’s see how to list files from a directory using a glob module.

import glob # search all files inside a specific folder # *.* means file name with any extension dir_path = r'E:\account\*.*' res = glob.glob(dir_path) print(res)
['E:\\account\\profit.txt', 'E:\\account\\sales.txt', 'E:\\account\\sample.txt']

Note: If you want to list files from subdirectories, then set the recursive attribute to True.

import glob # search all files inside a specific folder # *.* means file name with any extension dir_path = r'E:\demos\files_demos\account\**\*.*' for file in glob.glob(dir_path, recursive=True): print(file)
E:\account\profit.txt E:\account\sales.txt E:\account\sample.txt E:\account\reports_2021\december_2021.txt

Pathlib Module to list files of a directory

From Python 3.4 onwards, we can use the pathlib module, which provides a wrapper for most OS functions.

  • Import pathlib module: Pathlib module offers classes and methods to handle filesystem paths and get data related to files for different operating systems.
  • Next, Use the pathlib.Path(‘path’) to construct a directory path
  • Next, Use the iterdir() to iterate all entries of a directory
  • In the end, check if a current entry is a file using the path.isfile() function
import pathlib # folder path dir_path = r'E:\\account\\' # to store file names res = [] # construct path object d = pathlib.Path(dir_path) # iterate directory for entry in d.iterdir(): # check if it a file if entry.is_file(): res.append(entry) print(res)

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Python Get Files In Directory Tutorial

Python Get Files In Directory

Welcome to Python Get Files In Directory Tutorial. In this post, you will learn how to get files in directory using python. So let’s gets started this tutorial.

Python has various module such as os, os.path, shutil, pathlib etc by using which we can get files in directory. We will see how to work with these modules to get files.

Python Get Files In Directory – Getting Files With OS Module

In this section you will see how can you get files using OS module.

Directory Listing

OS module has two functions, by using which you can list your files.

os.listdir( )

  • os.listdir( ) is function of directory listing used in versions of Python prior to Python 3.
  • It returns a list containing the names of the entries in the directory given by path.

Let’s see an example of os.listdir( ) function. So write the following program.

Now let’s check the output, this will list all the files which are present in the specified directory.

Python Get Files In Directory

You can see all the files which are in document folder has been listed.

os.scandir( )

  • It is a better and faster directory iterator.
  • scandir( ) calls the operating system’s directory iteration system calls to get the names of the files in the given path.
  • It returns a generator instead of a list, so that scandir acts as a true iterator instead of returning the full list immediately.
  • scandir( ) was introduced in python 3.5 .

Let’s see an example of os.scandir( ), so write the following code.

The output of the above code is following –

Python Get Files In Directory

The ScandirIterator points to all the entries in the current directory.

If you want to print filenames then write the following code.

This will give you output as below.

Listing All Files In A Directory

Now you have to list all files in a directory that means printing names of files in a directory. So let’s write the following code.

Python Get Files In Directory

  • When os.listdir( ) is called then it returns all the files and directory from the specified path.
  • os.path.isfile( ) is called to filter that list and it only prints files not directories.
  • You can see output below, here only files are printed.

Listing Sub-directories

Now to list sub-directories, you have to write following program.

  • os.path.isdir( ) to confirm that a given path points to a directory that means it returns true if path is an existing directory.

Python Get Files In Directory

Here you can see only sub-directories are listed.

Python Get Files In Directory – Getting Files With Pathlib Module

In this section, you will learn directory listing using pathlib module.

  • pathlib module offers classes representing filesystem paths with semantics appropriate for different operating systems.
  • Python 3.2 or later is recommended, but pathlib is also usable with Python 2.7 and 2.6.
  • So let’s see how can we do directory listing using pathlib module.

Directory Listing

Write the following code for directory listing using pathlib module.

  • First of all you have to import path class from pathlib module.
  • Then you have to create a path object that will return either PosixPath or WindowsPath objects depending on the operating system.
  • path.iterdir( ) return the path points to a directory, yield path objects of the directory contents. It is used to get a list of all files and directories of specified directory.
  • Then simply print the entry name.

Now check the output, let’s see what will it show.

Python Get Files In Directory

Listing all Files In A Directory

Now let’s see how to list all files in a directory using pathlib module.

  • First of all call iterdir( ) method to get all the files and directories from the specified path.
  • Then start a loop and get all files using is_file( ) method. is_file( ) return True if the path points to a regular file, False if it points to another kind of file.
  • Then print all the files.

Now its time to check its output.

Python Get Files In Directory

All files are listed successfully.

Listing Sub-directories

Write the following code to list subdirectories.

Python Get Files In Directory

  • is_dir( ) is called to checks if an entry is a file or a directory, on each entry of the path iterator.
  • If it return True then the directory name is printed to the screen.
  • Now check the output.

Conclusion

In this tutorial, you have seen various ways of directory listing in python. OS and pathlib module is very useful in listing files. You have also seen many methods like listdir( ), scandir( ) and iterdir( ) that helps in getting files in directory.

So i am wrapping Python Get Files In Directory Tutorial here. I hope, you found very helpful informations about getting file in directory using python. But anyway, if you have any query then your queries are most welcome. I will try to solve out your issues. So just stay tuned with Simplified Python and enhance your knowledge of python. Thanks everyone.

Источник

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