0

I have two separate CSV files that I need to have imported and read based on user input. We'll call the two files test1.csv and test2.csv. The user will be prompted to input if they want test1 or test2.

After inputting which CSV file they want, the user will be prompted a few other questions to select which rows of data they need. My CSV file data looks like this:

     Column A, Column B, Column C, Column D`
     Row 1, 1, 2, 3
     Row 2, 4, 5, 6

If the user inputs Row 2, I'd like to return Columns B, C, and D as the result.

I'm new to python and unsure the coding to print the correct rows based off user input. I'm also unsure how to pick which CSV file gets pulled based on input.

As a work around, I wrote all the CSV data out in if/else statements within the code, but would prefer to keep the data in CSV format.

    'vehicle = input('Enter CSV File:')
         if vehicle == 'Test2':
         print ("Row Titles")
         print ("1.Row 1")
         print ("2.Row 2")
         choice = input('Row #:')
         Column B= '1'if choice == '1' else '2' if choice == '2' else 

0' Column C= '2' if choice == '1' else '5' if choice == '2' else '0' Column D= '3' if choice == '1' else '6' if choice == '2' else '0'

        print (column b+ column c+ column D)

elif vehicle == "Test2":

repeat code above with options for CSV Test2 file

else: print ('invalid input')'

2
  • Please, share the code that you wrote so that we can help you get unstuck. Commented May 28, 2019 at 12:25
  • edited the above question with code from my work around option Commented May 28, 2019 at 12:57

1 Answer 1

1

In terms of picking the csv, just have that be a prompt and place it in the file string.

fileinput = str(input("Which file do you want?"))
if not ".csv" in fileinput:
  fileinput += ".csv"

You'll want to import it as a pandas dataframe so you can easily call rows and columns.

import pandas as pd 
data = pd.read_csv(fileinput)

Then you can use iloc to return a row or column in the dataframe.

rowcol = input("Column or row?")
if rowcol == "column":
  column = int(input("Which column?"))
  result = data.iloc([column])
elif rowcol == "row":
  row = int(input("Which row?"))
  result = data.iloc[[row]]
else:
  print("Invalid response.")

print(result)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help, is there a way to do this without Pandas?
You could import it as a 2d numpy array via numpy.loadtxt. You can find the docs for it here. Your problem would look like this: data = numpy.loadtxt(open(filename, "rb"))

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.