0

I'm trying to use the range function with a variable assigned to an input. I have a .csv file and I'm trying to have it so that when the user gives their input as a number from 1-233 that the range will pick that line from the spreadsheet and print out the integer from only the first cell. However I can only get it to cycle down to the last line of the spreadsheet, regardless of what the input is. Below is the code.

var=input('Please give a number >0 and <= the number of students -->')

for line in file:
    line=range(var)
print(line)

How can I get it to only output the line that the user inputs?

3
  • What do you think line=range(var) is doing? In any case, you are iterating through the entire file: for line in file:... perhaps you meant to do something else with that... Commented Jun 21, 2021 at 22:57
  • This is not even close to correct code (given the question). Secondly, picking out a specific item from a csv file might be better done with the pandas module Commented Jun 21, 2021 at 23:03
  • 1
    @D.L no, that can trivially be handled with the python built ins. Commented Jun 21, 2021 at 23:04

3 Answers 3

1

This would do what you want but it's a bit fugly

with open('input.csv') as csvfile:
    content = csvfile.readlines()

this_needs_to_be_an_int = int(input(f'Please give a number >0 and <= {len(content)}\n'))

print(content[this_needs_to_be_an_int])

What it does is it reads the contents of the csv file into a list (using readlines()) and then gets the element of the list based on the input.

CSV files usually contain a header line, but if it doesn't you'll need to offset this_needs_to_be_an_int as lists are zero index based.

Sign up to request clarification or add additional context in comments.

Comments

0

This is a bit prettier than the openfile method, but it does require Pandas.

import pandas as pd

df = pd.read_csv('input.csv')

row_number = int(input('enter row number to print: '))
print(df.loc[[row_number]])

This imports the whole csv into a dataframe and extracts the row that the user wants. It is useful if already using this module, but otherwise, you can also do the same with the standard library modules csv or the readlines command for an open file.

2 Comments

What's readfile? I couldn't find it in the stdlib.
@wjandrea i meant readlines command (not a module) or csv module. will ammend that bit.
0

Use itertools.islice to skip the first n-1 lines; then next can be used to get the nth line.

from itertools import islice

var = int(input('Please give a number >0 and <= the number of students -->'))
print(next(islice(file, var-1)))

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.