ID : 410
viewed : 141
Tags : PythonPython FilePython Directory
100
You can mainly use two methods to open all files inside a directory in Python: the os.listdir()
function and the glob.glob()
function. This tutorial will introduce the methods to open all the files in a directory in Python. We’ve also included program examples you can follow.
os.listdir()
Function in PythonThe inside the os
module is used to list all the files inside a specified directory. This function takes the specified directory path as an input parameter and returns the names of all the files inside that directory. We can iterate through all the files inside a specific directory using the os.listdir()
function and open them with the open()
function in Python.
The following code example shows us how we can open all the files in a directory with the os.listdir()
and open()
functions.
import os for filename in os.listdir("files"): with open(os.path.join("files", filename), 'r') as f: text = f.read() print(text)
Output:
This is the first file. This is the second file. This is the last file.
We read the text from the three files inside the files/
directory and printed it on the terminal in the code above. We first used a for/in
loop with the os.listdir()
function to iterate through each file found inside the files
directory. We then opened each file in read
mode with the open()
function and printed the text inside each file.
glob.glob()
Function in PythonThe glob
module is used for listing files inside a specific directory. The inside the glob
module is used to get a list of files or subdirectories matching a specified pattern inside a specified directory. The glob.glob()
function takes the pattern as an input parameter and returns a list of files and subdirectories inside the specified directory.
We can iterate through all the text files inside a specific directory using the glob.glob()
function and open them with the open()
function in Python. The following code example shows us how we can open all files in a directory with the glob.glob()
and open()
functions:
import glob import os for filename in glob.glob('files\*.txt'): with open(os.path.join(os.getcwd(), filename), 'r') as f: text = f.read() print(text)
Output:
This is the first file. This is the second file. This is the last file.
We read the text from the three files inside the files/
directory and printed it on the terminal in the code above. We first used a for/in
loop with the glob.glob()
function to iterate through each file found inside the files
directory. We then opened each file in read
mode with the open()
function and printed the text inside each file.