Python Notes

Checking if a file or directory exists

It happens that you need to check the correctness of the address of a file or directory entered by the user. This can be done using the os.path.exists function, which returns true if the file system object exists, and false otherwise.

The os.path.isfile function checks if an object is a file, and os.path.isdir checks if it is a directory.

The script below checks for the presence of an object at the address specified by the user, then checks if it is a file or directory. Information is displayed depending on the type of object.

# The script checks if the path exists.
# If it's a file, print its size, creation, opening, and modification dates.
# If a directory, lists its subdirectories and files.

import os
import datetime

test_path = input('Enter address: ')

if os.path.exists(test_path):
    if os.path.isfile(test_path):
        print('FILE')
        print('Size:', os.path.getsize(test_path) // 1024, 'Kb')
        print('Creation date:',
              datetime.datetime.fromtimestamp(
                  int(os.path.getctime(test_path))))
        print('Date of last opening:',
              datetime.datetime.fromtimestamp(
                  int(os.path.getatime(test_path))))
        print('Last modified date:',
              datetime.datetime.fromtimestamp(
                  int(os.path.getmtime(test_path))))
    elif os.path.isdir(test_path):
        print('DIRECTORY')
        print('List of objects in it: ', os.listdir(test_path))
else:
    print('The object not found')

The script also uses the functions os.path.getsize (returns the file size), os.path.getctime (creation time), os.path.getatime (last opened time), os.path.getmtime (last modified date). The datetime.datetime.fromtimestamp method allows to display the time in the local format.

Š•xamples of program execution:

Enter address: /home/pl/test.py
FILE
Size: 2 Kb
Creation date: 2021-10-14 19:55:58
Date of last opening: 2022-04-21 08:21:00
Last modified date: 2021-10-14 19:55:58
Enter address: /home/pl/pas
DIRECTORY
List of objects in it:  ['vk', 'theory', 'tasks']