Web development and Tech news Blog site. WEBISFREE.com

HOME > python

Check for the existence of a Python file, isfile

Last Modified : 06 Mar, 2023 / Created : 06 Mar, 2023
1,009
View Count
Here is a way to check for the existence of a file in Python:



# Checking for the existence of a file in Python


Before deleting or reading a file, it is important to check if the file exists. This is because manipulating a non-existent file can cause errors. So, how can we check if a file exists?

The most commonly used method to check for the existence of a file is through the isfile() function in the os module.

os.path.isfile(fileName)

We will check the existence of a file and return True/False. Let's create a simple example below to understand.


! python isfile() examples


The following example is a simple code that checks if the file exists and only prints a message if it does. Please take a look at the code below.
import os

if os.path.isfile('my_file.php'):
  print("파일이 존재합니다.")

This is a very simple code. By using the if statement, you can determine whether or not to output a message depending on the presence of a file. If the file exists, the message 'The file exists' will be outputted.

Up to this point, we have learned how to confirm the existence of a file in Python.
Perhaps you're looking for the following text as well?

    Previous

    Creating custom error pages in Python Flask, 404

    Previous

    Finding Length of String in Python, len()