How do i read a directory in python?
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Practical Recipes for Working With Files in Python Show
Python has several built-in modules and functions for handling files. These functions are spread out over several modules such as In this tutorial, you’ll learn how to:
Python’s “with open(…) as …” PatternReading and writing data to files using Python is pretty straightforward. To do this, you must first open files in the appropriate mode. Here’s an example of how to use Python’s “with open(…) as …” pattern to open a text file and read its contents:
In the examples above, Getting a Directory ListingSuppose
your current working directory has a subdirectory called
The built-in Directory Listing in Legacy Python VersionsIn versions of Python prior to Python 3, >>>
>>>
A directory listing like that isn’t easy to read. Printing out the output of a call to >>>
Directory Listing in Modern Python VersionsIn modern versions of Python, an alternative to
>>>
The
Here,
Another way to get a directory listing is to use the
The objects returned by
In the example above, you call
Running the code above produces the following:
Using Here are the directory-listing functions again:
These functions return a list of everything in the directory, including subdirectories. This might not always be the behavior you want. The next section will show you how to filter the results from a directory listing. Listing All Files in a DirectoryThis section will show you how to print out the names of files in a directory using
Here, the call to
An easier way to
list files in a directory is to use
Using
Here’s how to list files in a directory using
Here, you call
The code above can be made more concise if you combine the The modified version looks like this:
This produces exactly the same output as the example before it. This section showed that filtering files or directories using Listing SubdirectoriesTo list subdirectories instead of files, use one of the methods below. Here’s how to use
Manipulating filesystem paths this way can quickly become cumbersome when you have multiple calls to
Here’s how to use
As in the file listing example, here you call
Here’s how to use
Calling
Getting File AttributesPython makes retrieving file attributes such as
file size and modified times easy. This is done through
The examples below show how to get the time the files in >>>
The >>>
In the example above, the code loops through the object returned by
This will first get a list of files in The arguments passed to
Together, these directives produce output that looks like this: >>>
The syntax for converting dates and times into strings can be quite confusing. To read more about it, check out the official documentation on it. Another handy reference that is easy to remember is http://strftime.org/ . Making DirectoriesSooner or later, the programs you write will have to create directories in order to store data in them.
Creating a Single DirectoryTo create a single directory, pass a path to the directory as a parameter to
If a directory already exists,
If
the path already exists, >>>
To avoid errors like this, catch the error when it happens and let your user know:
Alternatively, you can ignore the
This will not raise an error if the directory already exists. Creating Multiple Directories
This will create a nested directory structure that contains the folders 2018, 10, and 05:
This creates the Run
This prints out a directory tree of the current directory. As you can see, all of the directories have
Passing By default, Running the code above produces a directory structure like the one below in one go:
I prefer using Filename Pattern MatchingAfter getting a list of files in a directory using one of the methods above, you will most probably want to search for files that match a particular pattern. These are the methods and functions available to you:
Each of these is discussed below. The examples in this section will be performed on a directory called
If you’re following along using a Bash shell, you can create the above directory structure using the following commands:
This will create the Using String MethodsPython has several built-in methods for modifying and manipulating strings. Two of these methods, >>>
The code above finds all the files in
Simple Filename Pattern Matching Using fnmatchString methods are limited in their matching abilities. >>>
This iterates over the list of files in More Advanced Pattern MatchingLet’s suppose you want to find Using >>>
Here, you print only the names of files that match the
Filename Pattern Matching Using globAnother useful module for pattern matching is
UNIX and related systems translate name patterns with wildcards like For example, typing Here’s an example of how to use
>>>
>>>
This finds all text (
>>>
This example makes use of Running the program above produces the following:
>>>
Calling
To recap, here is a table of the functions we have covered in this section:
Traversing Directories and Processing FilesA common programming task is walking a directory tree and processing files in the tree. Let’s explore how the built-in Python function
The following is an example that shows you how to list all files and directories in a directory tree using
On each iteration, it prints out the names of the subdirectories and files it finds:
To traverse the directory tree in a bottom-up manner, pass in a
Passing the
As you can see, the program started by listing the contents of the subdirectories before listing the contents of the root directory. This is very useful in situations where you want to recursively delete files and directories. You will learn how to do this in the sections below. By default, Making Temporary Files and DirectoriesPython provides a handy module for creating temporary files and directories called
Here’s how to create a temporary file:
The first step is to import In the example above, the mode is After writing to the file, you can read from it and close it when you’re done processing it. Once the file is closed, it will be deleted from the filesystem. If you need to name the temporary files produced using The temporary files and directories created using On Windows, the directories are
This creates a temporary file and reads data from it. As soon as the file’s contents are read, the temporary file is closed and deleted from the file system.
>>>
Calling After the context manager goes out of context, the temporary directory is deleted and a call to Deleting Files and DirectoriesYou can delete single files, directories, and entire directory trees using the methods found in the Deleting Files in PythonTo delete a single file, use
Deleting a file using
Calling
The following example shows how to use exception handling to handle errors when deleting files:
The code above attempts to delete the file first before checking its type. If Finally, you can also use
This creates a Deleting DirectoriesThe standard library offers the following functions for deleting directories:
To delete a single directory or folder, use
Here, the >>>
Alternatively, you can use
Here, you create a Deleting Entire Directory TreesTo delete non-empty directories and entire directory trees, Python offers
Everything in
This walks down the directory tree and tries to delete each directory it finds. If the directory isn’t empty, an
Copying, Moving, and Renaming Files and DirectoriesPython ships with the Copying Files in Python
To preserve all file metadata when copying, use
Using Copying DirectoriesWhile Here’s an example of how to copy the contents of one folder to a different location: >>>
In this example, Moving Files and DirectoriesTo move a file or directory to another location, use
>>>
Renaming Files and DirectoriesPython includes >>>
The line above will rename Another way to rename files or directories is to use >>>
To rename files using ArchivingArchives are a convenient way to package several files into one. The two most common archive types are ZIP and TAR. The Python programs you write can create, read, and extract data from archives. You will learn how to read and write to both archive formats in this section. Reading ZIP FilesThe
Here, you create a
To get a list of files in the archive, call
This produces a list:
Here’s the output:
The following example shows how to retrieve more details about archived files in a Python REPL. Assume that the >>>
The first line shows how to retrieve a file’s last modified date. The next line shows how
to get the size of the file after compression. The last line shows the full path of
Creating New ZIP ArchivesTo create a new ZIP archive, you open a >>>
In the example, To add files to an existing archive, open a >>>
Here, you open the Opening TAR ArchivesTAR files are uncompressed file archives like ZIP. They can be compressed using gzip, bzip2, and lzma compression methods. The Do this to read from an archive:
Use the
>>>
This returns a list with the names of the archive contents. The metadata of each entry in the archive can be accessed using special attributes: >>>
In this example, you loop through the list of files returned by Creating New TAR ArchivesHere’s how you do it: >>>
First, you make a list of files to be added to the archive so that you don’t have to add each file manually. The next line uses the After the archive is created and populated, the To add new files to an existing archive, open the archive in append mode ( >>>
Opening an archive in append mode allows you to add new files to it without deleting the ones already in it. Working With Compressed Archives
For example, to read or write data to a TAR archive compressed using gzip, use the >>>
The An Easier Way of Creating ArchivesThe Python Standard Library also supports creating TAR and ZIP archives using the high-level methods in the Working With Archives Using
By default, it compresses all the files in the current directory into the archive format specified in the This is how to create a TAR archive using
This copies everything in
Calling Reading Multiple FilesPython supports reading data from multiple input streams or from a list of files through the
Using Let’s use
Running this on two text files in my current directory produces the following output:
ConclusionYou now know how to use Python to perform the most common operations on files and groups of files. You’ve learned about the different built-in modules used to read, find, and manipulate them. You’re now equipped to use Python to:
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Practical Recipes for Working With Files in Python How do I read a specific directory in Python?It takes only a single argument as new directory path.. Import modules.. Add path of the folder.. Change directory.. Get the list of a file from a folder.. Iterate through the file list and check whether the extension of the file is in . txt format or not.. If text-file exist, read the file using File Handling.. How do I print the contents of a directory in Python?For this article, the following methods from the os module will be required:. os. startfile(): This method prints the contents of a given file. Syntax: os.startfile(path, operation='open') ... . os. listdir(): This method lists all the files and directories within a given directory. ... . os. path.. How do I list all files of a directory?To list all files in the current directory, type the following: ls -a This lists all files, including. dot (.) ... . To display detailed information, type the following: ls -l chap1 .profile. ... . To display detailed information about a directory, type the following: ls -d -l .. How do I read a list of files in Python?To get a list of all the files and folders in a particular directory in the filesystem, use os. listdir() in legacy versions of Python or os. scandir() in Python 3. x.
|