2

I have a file called students.csv that I am trying to pass into a python script s1.py. On the command line I type python3 s1.py students.csv, however I get the error

File "s1.py", line 7, in <module>
    with open(file, 'r') as studentGrades:
TypeError: invalid file: ['s1.py', 'students.csv']

Here is the code in s1.py:

#!/usr/bin/env Python3

import sys

file = sys.argv

with open(file, 'r') as studentGrades:
        for line in studentGrades:
                print(line)

How do I pass in this file correctly so I can use it in my python script?

2 Answers 2

3

Do file = sys.argv[1] instead.

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

Comments

0

As @EricWang said, you can do file = sys.argv[1] to get the filename if it was included. However, there are a number of edge cases this doesn't account for:

  • This code will fail if the user forgets to type the argument
  • This code will fail if you have other arguments and the user doesn't type them in in a specific order
  • This code will fail if the argument isn't a valid filename or the file doesn't exist.

To get around these, my suggestion is that you use argparse. This will enable you to name your arguments, allowing the user to enter them in any order. It has validation code, so you can make sure that the filename they entered is an actual file. It also has the concept of "required arguments" so if your user forgets to enter them then you can specify a handy error message to inform them how dumb misguided they are.

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.