Say you had a file fruits.csv with the following contents:
apples,bananas,cherries
5,3,10
The following code that utilizes os.path.isfile would allow you to ensure the user has entered a valid file path before attempting pandas.read_csv:
import os
import pandas as pd
csv_filepath = input("Please enter a valid file path to a csv: ")
while not os.path.isfile(csv_filepath):
print("Error: That is not a valid file, try again...")
csv_filepath = input("Please enter a valid file path to a csv: ")
try:
df = pd.read_csv(csv_filepath)
print(df)
# Add your other code to manipulate the dataframe read from the csv here
except BaseException as exception:
print(f"An exception occurred: {exception}")
Example Usage:
Please enter a valid file path to a csv: vegetables.csv
Error: That is not a valid file, try again...
Please enter a valid file path to a csv: fruits.csv
apples bananas cherries
0 5 3 10
filepath = input("Enter filepath name: ")?