How to Check if an Item is a File in Python?

Estimated read time 1 min read

To check if an item is a file in Python, you can use the os.path.isfile() function. This function returns True if the specified path is an existing regular file, and False otherwise. Here is an example:

import os

path = '/path/to/file.txt'
if os.path.isfile(path):
    print('The specified path is a file')
    print('The specified path is not a file')

In the above example, replace '/path/to/file.txt' with the path of the file you want to check. If the path is a file, the code will print 'The specified path is a file', otherwise it will print 'The specified path is not a file'.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply