Posts

Showing posts with the label Python(pathlib Module)

How to safely create a nested directory in Python

Image
 In order to create a nested directory safely in Python, we could do this: i mport os if not os . path . exists (' directory' ): os . makedirs (' directory' ) Or after Python 3.5, you could use: from pathlib import Path Path("C:/new/new_dir").mkdir(parents=True, exist_ok=True) If parents=True , the directory new_dir 's parents will be automatically created if they are not existant.  If parents=Flase , it raises FileNotFoundError exception. The exist_ok paramenter was added in version 3.5,  if it is set to False (default setting), FileExistsError is raised when the file is already present. If it is set to True , FileExistsError will be ignored.  

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