1

I am new to coding and am trying out some pandas stuff and would like to know how to ask the user for the file-path of a file which I will be using pandas with later, and to subsequently open that file, which will be a csv file. Any help would be appreciated.

Here's the code:

import csv

import pandas as pd
filepath = ("Enter filepath name: ")
df = pd.read_csv (rfilepath)
print (df)

1
  • filepath = input("Enter filepath name: ")? Commented Nov 22, 2020 at 13:59

2 Answers 2

1

You got it pretty much spot on already!

import pandas as pd
    
filepath = input('Enter filepath name: ')
df = pd.read_csv(filepath)
print(df)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.