File Handling

Check file exists

You can use two methods from the os.path module to check if a file exists

  • exists()

  • isfile()

exists()

The exists() method returns True if either a provided file or a directory exists, otherwise it returns False.

1import os
2
3# checks for a file
4print(os.path.exists("./python_files/example.txt"))
5
6# checks for a directory
7print(os.path.exists("./python_files/example_folder"))

Note:

  • "./python_files/example.txt" is a path to a file

  • "./python_files/example_folder" is a path to a folder

isfile()

The isfile() method returns True if the provided file exists. If the file does not exist, or the path points to a directory, then it will return False.

1import os
2
3# checks for a file
4print(os.path.isfile("./python_files/example.txt"))
5
6# checks for a directory
7print(os.path.isfile("./python_files/example_folder"))

Delete file

To delete a file use the remove() function in the os module.

1import os
2
3os.remove("./python_files/example.txt")