Python get all files in directory with extension

How To List Files With A Certain Extension in Python

before going to list a files with certain extension, first list all files in the directory then we can go for the required extension file. In python to list all files in a directory we use os.listdir library. In this we have to mention the path of a directory which you want to list the files in that directory. For this we have to import os.

import os x = os.listdir(r"C:\Users\enaknar\Desktop\pycharm") print (x) for i in x: print(i)

Output:

[ '1-1.py', '1-2.py', '1-3.py', 'asf', 'asf.txt', 'fsg.py', 'read-1.py'] 1-1.py 1-2.py 1-3.py asf asf.txt fsg.py read-1.py

Here we are storing all the files of a directory “C:\Users\enaknar\Desktop\pycharm” in variable x as a list.

we are printing the list x and we are printing list one by one using for loop. in this way we can print or list all files in a particular directory.

List Files With A Certain Extension in Python

in the previous example we have seen how to list all files in a directory, now in this example i will show you how to print or list the files with certain extension.

#find a file ends with .txt import os x = os.listdir(r"C:\Users\devops\Desktop\pycharm") for i in x: if i.endswith(".txt"): print(i)

to check a file with certain extension in python we use endswith method. The endswith() method returns True if a string ends with the specified suffix. If not, it returns False.

asf.txt Process finished with exit code 0

so here writing one more if loop like if it is finds a file with extension with “.txt” it will print the file.

Читайте также:  Birthday Reminders for August

in this way we can print or list f iles with a certain extension in python.

  • List Files With A Certain Extension in Python
  • list all files in a directory in python
  • python list files in a directory
  • list files in a directory python

Источник

Python list Files in Directory with Extension txt

In this Python tutorial, we will see how to list all files of a directory having a specific extension.

Sometimes we need to list files having a specific extension before performing any operation on them. For example, if you wanted to copy only text files from one location to another. In this case, we need to make sure we are only looking for files having a .txt extension.

We will use the following three methods.

Table of contents

How to list files in directory with extension txt

A file extension, or filename extension, is a suffix at the end of a file. It comes after the period. Extension specifies a file type such as text, CSV file, pdf, or image file. For example, for a text file, it is txt . For image file it is jpg , jpeg , or bmp .

Here are the steps to get the list of files having the txt extension using a glob module.

  1. Import glob module The glob module, part of the Python Standard Library, is used to find the files and folders whose names follow a specific pattern. The searching rules are similar to the Unix Shell path expansion rules.
  2. Construct a pattern to search for the files having the specific extension For example, directory_path/*.txt to list all text files present in a given directory path. Here the * means file name can be anything, but it must have a txt extension.
  3. Use glob() method The gob.glob(pathname) method returns a list of files that matches the path and pattern specified in the pathname argument. in this case, it will return all text files.

Example: list files in directory with extension txt

The following text files are present in my current working directory.

sales.txt profit.txt samples.txt

Example 1: List all txt files present in the ‘account’ directory.

import glob # absolute path to search all text files inside a specific folder path = r'E:/demos/files_demos/account/*.txt' files = glob.glob(path) print(files) 
['E:/account\\profit.txt', 'E:/account\\sales.txt', 'E:/account\\sample.txt']

If you want to list files from a current directory the use glob.glob(‘./*.txt’) .

Note: This solution is fast because it only looks for a specific pattern instead of traversing the entire directory file by file to check if it has a specific extension, resulting in performance benefits.

Os module to list files in directory with extension

This module helps us to work with operating system-dependent functionality in Python. The os module provides functions for interacting with the operating system.

  • Use the os.listdir(‘path’) function to get the list of all files of a directory. This function returns the names of the files and directories present in the directory.
  • Next, use a for loop to iterate all files from a list.
  • Next, use the if condition in each iteration to check if the file name ends with a txt extension. If yes, add it to the final list
import os # folder path dir_path = r'E:\account' # list to store files res = [] # Iterate directory for file in os.listdir(dir_path): # check only text files if file.endswith('.txt'): res.append(file) print(res)
['profit.txt', 'sales.txt', 'sample.txt']

Note: This solution is slow because it traverses the entire directory file by file to check if it has a specific extension, resulting in performance overhead if the directory contains many files. So I suggest you use the first solution, i.e., glob module.

list files in directory and subdirectories with extension txt

We can use the following two approaches: –

Glob module to list files from subdirectories with txt extension

Set the recursive attribute of a glob() method to True to list text files from subdirectories.

Use Python 3.5+ to find files recursively using the glob module. If you are using the older version of Python, then use the os.walk() method.

The glob module supports the ** directive. If you want it recursive you can use glob.glob(‘**/*.txt’) and set a recursive flag to True , the glob() method parses the given path and looks recursively in the directories.

import glob # absolute path to search all text files inside a specific folder path = r'E:/account/**/*.txt' files = glob.glob(path, recursive=True) print(files)
['E:/account\\profit.txt', 'E:/account\\sales.txt', 'E:/account\\sample.txt', 'E:/account\\reports_2021\\december_2021.txt']

os.walk() to list files in directory and subdirectories with extension txt

It is a recursive function, i.e., Every time the generator is called it creates a tuple of values (current_path, directories in current_path, files in current_path) and 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.

  • Call the os.walk(»path’) function. It will yield two lists for each directory it visits. The first list contains files, and the second list includes directories.
  • Next, Iterate the list of files using a for loop
  • Next, use the if condition in each iteration to check if the file name ends with a txt extension. If yes, add it to the final list.
import os # list to store txt files res = [] # os.walk() returns subdirectories, file from current directory and # And follow next directory from subdirectory list recursively until last directory for root, dirs, files in os.walk(r"E:\demos\files_demos\account"): for file in files: if file.endswith(".txt"): res.append(os.path.join(root, file)) print(res) 
['E:/account\\profit.txt', 'E:/account\\sales.txt', 'E:/account\\sample.txt', 'E:/account\\reports_2021\\december_2021.txt']

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

Источник

How to Get Python List all Files in Directory with Extension?

To get the list of file names in the given folder or directory, we can use different approaches. The easiest way of doing it, use the Python os module.

The Python os module is very useful and it has a lot of features for accessing file systems and other operating systems details.

os.listdir()

Python os module has a method called listdir() . It returns the Pyhton list of all the files in the directory. The syntax for this method is pretty simple and you can get it from the below code.

Irrespective of the Operating System like Windows, MacOS and Linux (Ubuntu, RedHat, and other distros); this method work flawlessly

import os list_files = os.listdir() print(list_files)

Note: Make sure your Python script is saved in the same directory. You can also specify the directory name in the listdir() method.

The above code prints the Python list which includes all the file names from the current folder or directory with extension. It also includes subdirectories.

You can also print the file names one by one as a string using Python for-loop.

import os list_files = os.listdir() for file_name in list_files: print(file_name)

Once you get the list of file names, you can perform different file operations like reading, writing and deleting files.

You can use the Python split() method to get the extension of the file. Split the file_name name over “.” Like,

This is a very useful yet simple automation trick to get the Python list all files in directory with extension. You will find it handy. Any question? Let me know in the comment. Thanks!

Источник

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