首页 > 解决方案 > 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

标签: pythonpandasdataframe

解决方案


您可以使用 python 的 os 模块来检查文件是否存在。

以下是示例:

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

这将根据文件是否存在返回真或假。


推荐阅读