user8233898
user8233898

Reputation: 43

How do I read a command line argument from Python?

I am new to python programming, but basically I want to have a script where when given a file path from the command line (the file being a .csv file), the script will take this file and turn it into a list.

Code I have seen for this problem usually doesn't take the file from the command line, rather it just has the exact filename in the code. I want to use this code on many different files, so hard coding the file name into the program is not an option.

Upvotes: 0

Views: 2034

Answers (1)

cs95
cs95

Reputation: 403128

The only change you need to make to the code that you've already found is this:

import sys
filepath = sys.argv[1]
... # process file

And now, you invoke your script like this: ./script.py /path/to/file.

sys.argv is used to read command line arguments. Optional commands start from index 1, because argv[0] stores the name of your script (script.py).

Upvotes: 2

Related Questions