Os
You can list all files in the current directory using os.listdir:
import os for filename in os.listdir(os.getcwd()): with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode # do your stuffGlob
Or you can list only some files, depending on the file pattern using the glob module:
import os, glob for filename in glob.glob('*.txt'): with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode # do your stuffIt doesn't have to be the current directory you can list them in any path you want:
import os, glob path = '/some/path/to/file' for filename in glob.glob(os.path.join(path, '*.txt')): with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode # do your stuffPipe
Or you can even use the pipe as you specified using fileinput
import fileinput for line in fileinput.input(): # do your stuffAnd you can then use it with piping:
ls -1 | python parse.pyView Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Prerequisite:
- File Handling
- os
Python is a strong language which is extremely capable even when it comes to file handling. In this article, we will learn how to read multiple text files from a folder using python.
Approach:
- 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 usingFile Handling
Functions used:
- os.chdir() method in Python used to change the current working directory to specified path. It takes only a single argument as new directory path.
Syntax: os.chdir(path)
Parameters:
- path: A complete path of directory to be changed to new directory path.
Returns: Doesn’t return any value
- os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned.
Syntax: os.listdir(path)
Parameters:
- path (optional) : path of the directory
Return Type: This method returns the list of all files and directories in the specified path. The return type of this method is list.
Below is the Implementation:
Program:
Python3
import os
path = "Enter Folder Path"
os.chdir(path)
def read_text_file(file_path):
with open(file_path, 'r') as f:
print(f.read())
for file in os.listdir():
if file.endswith(".txt"):
file_path = f"{path}\{file}"
read_text_file(file_path)
Output:
//media.geeksforgeeks.org/wp-content/uploads/20210125102530/FreeOnlineScreenRecorderProject4.mp4
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
In this article, we will cover how do we list all files in a directory in python.
What is a directory?
A Directory also sometimes known as a folder is a unit organizational structure in a computer’s file system for storing and locating files or more folders. Python now supports a number of APIs to list the directory contents. For instance, we can use the Path.iterdir, os.scandir, os.walk, Path.rglob, or os.listdir functions.
Directory in use: gfg
Method 1: Os Module
- os.listdir() method gets the list of all files and directories in a specified directory. By default, it is the current directory. Beyond the first level of folders, os.listdir() does not return any files or folders.
Syntax: os.listdir(path)
Parameters:
- Path of the directory
Return Type: returns a list of all files and directories in the specified path
Example 1: Get all the list files in a Directory
Python
Output:
Example 2: To get only .txt files.
Python3
import os
for x in os.listdir():
if x.endswith(".txt"):
print(x)
Output:
- OS.walk() generates file names in a directory tree. This function returns a list of files in a tree structure. The method loops through all of the directories in a tree.
Syntax: os.walk(top, topdown, onerror, followlinks)
- top: It is the top directory from which you want to retrieve the names of the component files and folders.
- topdown: Specifies that directories should be scanned from the top down when set to True. If this parameter is False, directories will be examined from the top down.
- onerror: It provides an error handler if an error is encountered
- followlinks: if set to True, visits folders referenced by system links
Return: returns the name of every file and folder within a directory and any of its subdirectories.
Python3
Output:
- os.scandir() is supported for Python 3.5 and greater.
Syntax: os.scandir(path = ‘.’)
Return Type: returns an iterator of os.DirEntry object.
Python3
import os
obj = os.scandir()
print("Files and Directories in '% s':" % path)
for entry in obj:
if entry.is_dir() or entry.is_file():
print(entry.name)
Output:
Method 2: Using glob module
The glob module is used to retrieve files/path names matching a specified pattern.
- glob() method: With glob, we can use wild cards (“*, ?, [ranges])to make path retrieval more simple and convenient.
Example:
Python3
import glob
path = "C:\\Users\\Vanshi\\Desktop\\gfg"
print('\nNamed with wildcard *:')
for files in glob.glob(path + '*'):
print(files)
print('\nNamed with wildcard ?:')
for files in glob.glob(path + '?.txt'):
print(files)
print('\nNamed with wildcard ranges:')
for files in glob.glob(path + '/*[0-9].*'):
print(files)
Output:
- iglob() method can be used to print filenames recursively if the recursive parameter is set to True.
Syntax: glob.iglob(pathname, *, recursive=False)
Example:
Python3
import glob
path = "C:\\Users\\Vanshi\\Desktop\\gfg**\\*.txt"
print("\nUsing glob.iglob()")
for file in glob.iglob(path, recursive=True):
print(file)
Output: