Found 9764 Articles for Python

How can I iterate over files in a given directory in Python?

Alekhya Nagulavancha
Updated on 19-Apr-2023 14:21:12
Iterating over files in a given directory can be helpful for doing things like finding files that match a certain criterion, or counting the number of files in a directory. Python provides the following five ways to walk through all the existing files in a directory os.listdir() method os.walk() method os.scandir() method Using pathlib module glob.iglob() method Let us look at these methods in detail. Using os.listdir() Method The os.listdir() method is used to list all the files present in a directory. It accepts the path of the directory as an argument and all the entries, apart from ... Read More

How to list directory tree structure in python?

Rajendra Dharmkar
Updated on 16-Dec-2019 06:59:23
You can use the os.walk() method to get the list of all children of path you want to display the tree of. Then you can join the paths and get the absolute path of each file.For exampleimport os def tree_printer(root):     for root, dirs, files in os.walk(root):         for d in dirs:             print os.path.join(root, d)             for f in files:             print os.path.join(root, f) tree_printer('.')This will print a list of all the directories in your tree first and the print ... Read More

How to check if a given directory contains any other directory in Python?

Rajendra Dharmkar
Updated on 16-Dec-2019 06:53:16
To check if a directory contains any directory or not, simply check the reverse, ie, if it contains any entry that is not a file using the isfile method.For exampleimport os list_dir = os.listdir('.') for f in list_dir:     if not os.path.isfile(os.path.join('.', f)):         print("Not a file")You can also use the all built in to check this.For exampleimport os list_dir = [os.path.isfile(os.path.join('.', f)) for f in os.listdir('.')] print(all(list_dir))The all function will return true only if all entries are files in the given directory.Read More

How do you get a directory listing sorted by their name in Python?

Rajendra Dharmkar
Updated on 16-Dec-2019 06:52:07
You can call the os.listdir function to get the list of the directory contents and use the sorted function to sort this list.For example>>> import os >>> list_dir = os.listdir('.') >>> list_dir = [f.lower() for f in list_dir]   # Convert to lower case >>> sorted(list_dir) ['dlls', 'doc', 'etc', 'include', 'lib', 'libs', 'license.txt', 'news.txt', 'python.exe', 'pythonw.exe', 'readme.txt', 'scripts', 'share', 'tcl', 'tools', 'w9xpopen.exe']

How do you get a directory listing sorted by creation date in Python?

Rajendra Dharmkar
Updated on 18-Feb-2020 05:38:28
To get a directory listing sorted by creation date in Python, you can call os.listdir() to get a list of the filenames. Then call os.stat() for each one to get the creation time and finally sort against the creation time. exampleimport os import time import sys from stat import S_ISREG, ST_CTIME, ST_MODE dir_path = '.' # get all entries in the directory entries = (os.path.join(dir_path, file_name) for file_name in os.listdir(dir_path)) # Get their stats entries = ((os.stat(path), path) for path in entries) # leave only regular files, insert creation date entries = ((stat[ST_CTIME], path)            for stat, ... Read More

How to know/change current directory in Python shell?

Sarika Singh
Updated on 17-Aug-2022 13:05:49
A portable method of interacting with the operating system is offered through the OS Python Module. The module, which is a part of the default Python library, contains tools for locating and modifying the working directory. The following contents are described in this article. How to obtain the current working directory os.getcwd() Changing the current working directory : os.chdir() The __file__ function returns the path to the current script file (.py). Getting the current working directory- os.getcwd() The function os.getcwd() returns as a string str the absolute path to Python's current working directory. "Get current working directory" ... Read More

How to check if a file is a directory or a regular file in Python?

Rajendra Dharmkar
Updated on 16-Dec-2019 06:28:25
You can check if a file is a directory or a file using the os.path.isfile method:Example>>> import os >>> print os.path.isfile('my_file.txt') True >>> print os.path.isfile('my_folder') False

How to safely open/close files in Python?

Rajendra Dharmkar
Updated on 16-Dec-2019 06:32:44
open() opens a file. You can use it like:f = open('my_file', 'r+') my_file_data = f.close()The above code opens 'my_file' in read mode then stores the data it reads from my_file in my_file_data and closes the file. The first argument of open is the name of the file and second one is the open mode. It determines how the file gets opened.For example– If you want to read the file, pass in r – If you want to read and write the file, pass in r+ – If you want to overwrite the file, pass in w – If you ... Read More

How to delete all files in a directory with Python?

Rajendra Dharmkar
Updated on 16-Dec-2019 06:30:16
You can delete a single file or a single empty folder with functions in the os module.ExampleFor example, if you want to delete a file my_file.txt, >>> import os >>> os.remove('my_file.txt')The argument to os.remove must be absolute or relative path.To delete multiple files, just loop over your list of files and use the above function. If you want to delete a folder containing all files you want to remove, you can remove the folder and recreate it as follows:>>> import shutil >>> shutil.rmtree('my_folder') >>> import os >>> os.makedirs('my_folder')You can also recursively delete the files using os.walk().Exampleimport os, re, os.path mypath ... Read More

How to open a file in the same directory as a Python script?

Rajendra Dharmkar
Updated on 16-Dec-2019 06:24:28
The best and most reliable way to open a file that's in the same directory as the currently running Python script is to use sys.path[0]. It gives the path of the currently executing script. You can use it to join the path to your file using the relative path and then open that file.ExampleFor example if you have a file called my_file.txt in the same directory as currently executing script, you can open it using:import os with open(os.path.join(sys.path[0], "my_file.txt"), "r") as f:     print( will open the file and read its content given that the file resides in the ... Read More