0

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
4

2 回答 2

1

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

以下是示例:

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

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

于 2020-09-23T18:25:41.863 回答
1

最好的方法是使用 try except 像这样:

try:
    df = pd.read_csv('filepath/file/test.csv')
except FileExistsError as err:
    print(err)

但您也可以像这样检查文件是否存在:

if os.path.exists('filepath/file/test.csv'):
    df = pd.read_csv('filepath/file/test.csv')
else:
    print('File is not exist')
于 2020-09-23T18:19:56.537 回答