To check if a file exists or not is an extremely easy task to be done in Python, but there are some tricky parts… Below is one of the possible approaches to this.
The script below to check if a file exists.
from pathlib import Path fileName = "c:\temp\file.txt" file = Path(fileName) isFile = file.is_file()
The variable isFile is set to True file passed has argument exists or False if it doesn’t. The problem with this approach is, if you don’t pass the full path of the file (example: fileName = “file.txt” will return false, even if the file exists.
To use the relative path, first we need to get the directory where the script is running:
import os base_dir = os.path.dirname(os.path.realpath(__file__))
The variable __FILE__ exists in Python and holds the reference to the script file that is being executed.
If we join the two approaches, we can implement a pseudo-retry pattern.
def checkFile(file): pFile = Path(file) isFile = pFile.is_file() if(not isFile): BASE_DIR = os.path.dirname(os.path.realpath(__file__)) pFile = Path(BASE_DIR +"\\" + file) isFile = pFile.is_file() return isFile
The function above will try to verify whether the file passed via argument exists. If it doesn’t, it concatenates the path to the current script’s path and tries again.
Referência:
Latest posts by Breno RdV (see all)
- What is a metaclass and how it works. (#python #dev #metaclass) - January 11, 2023
- Understanding the magic of Generators. (#python, #dev, #generator, #iterator) - December 28, 2022
- Facebook comments on posts. (info) - June 23, 2020