Posts

Showing posts with the label Python(OS Module)

How to list all files in a directory in Python

Image
  In python, os.listdir() will list everything(files and directories) that is in a directory. >>> import os >>> os.listdir() ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll'] If you just want files only, you could filter the list like this, >>> from os.path import isfile, join >>> files_only = [file for file in os.listdir() if isfile(join(os.getcwd(),file))] >>> files_only ['LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe', 'vcruntime140.dll'] And also you could use os.walk() , >>> (_,_,files) = next(os.walk(os.getcwd())) >>> files ['LICENSE.txt', 'NEWS.txt', 'python.exe&

Check a file's existance without handling exceptions in Python

Image
  In order to check a file's existance without opening it and handling exception, python provides us os.path.isfile('path/to/file') in the standard os.path module. >>>   os.path.isfile('/home/pete/file01.py') >>> True  It returns True if the file exists, otherwise returns False . You check a directory's existance using  os.path.isdir('path/to/directory') >>>   os.path.isfile('/home/pete/pictures') >>> True  It returns  True  if the directory exists, otherwise returns  False . And also you can check a file or a directory's existance, using  os.path.exists('/path/to/file/or/directory') >>>   os.path.exists('/home/pete/pictures') >>> True Starting with Python 3.4, it provides a object-oriented approach to acheive this end. >>> from pathlib import Path >>> file_path = Path('/home/pete/file01.py') >>> file_path.is_file() True >>> file