Skip to content
Advertisement

How to check the folder for file and then read the file in python

I need to read a csv from a folder location, but there is catch in it. It could also happen my other module which writes the csv into that folder fails and unable to export the file, so basically i have to check the folder that if a csv file called “test.csv” exist or not in that folder, if it exist read the file else print(‘file not found’)

folder name = file, file_name= test.csv
try:
    df = pd.read_csv('filepath/file/test.csv') --- read if it is present in the folder
 except error:
 result = 'File not Found' --- catch message in a variable

Advertisement

Answer

you can use os module of python to check if a file exists or not.

below is example:

import os.path
os.path.isfile('./final_data.csv')

this will return true or false based on file exists or not.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement