sharing everything

Python List Files in Directory

When I create a program with Python to read multiple file in directory, I get problem how Python list file in directory. After searching at Python documentation, I get documentation how Python implementated list file in directory. We can use module os (import os) to Python List Files in Directory. This module provides a portable way of using operating system dependent functionality. This is a sample method how Python List Files in Directory with some method.

First method is use os.listdir and fnmatch.fnmatch function. We can get all list files in directory with command os.listdir. With command fnmatch.fnmatch, we can filter data by name specified. This is a code how to implementated this :

From this first function, we will get all list files in Directory with name specified. You can change * symbol at fnmatch.fnmatch with *.txt or other if you want to filter your list files.

Second method is how Python list files in directory with all files in subdirectory. We can use function os.walk to solve this problem. This my code how Python list files in Directory with subdirectory :

The third method is use glob module to solve problem Python list files in directory. With this code, we add feature how Python identifead if a text file name is a directory or filename. We can use function os.path.isdir to identified if a string/text is a directory or filename. This is a Python list files in Directory with module glob.

With this code, Python will print directory if get a inputtext is a directory address or file if get file.

The fourth method is like with first method (use os.listdir). But in this code, we can sort list files or directory before printted to command line. This is a sample code how Python list files in directory with sorting data before printted to command line/terminal.


This is some of simple method how Python list file in directory of subdirectory.
My name is Toto Sugito. This is my notes when I try something. Maybe, this is NOT THE BEST SOLUTION for your problems. If you have other method or idea that better with my post, please share in this blog. Thank for visiting my site.

No Comments Yet

Leave a Reply

Your email address will not be published. Required fields are marked *

 

Categories

Bloggers - Meet Millions of Bloggers