PierreTroodoo
PierreTroodoo

Reputation: 191

How to open a file that is input by the user in command-line?

So if the user is running my file (test.py) from the command line, and wants to open a file in that program, how do I open it?

Say if the user writes 'test.py < file2.py' in command line, how do I then open file2.py in test.py?

I know it's something to do with sys.argv.

Upvotes: 0

Views: 1493

Answers (2)

Hackaholic
Hackaholic

Reputation: 19763

you need to use sys.argv

sys.argv

The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

it should be :

python test.py your_file

sys.argv[0], its the script name that is test.py

sys.argv[1], will have your_file

now you can use open built-in to open file:

my_file = open(sys.argv[1], 'r')

suppose you entered the file and number both:

python test.py your_file 2

here : sys.argv[0] -> test.py

sys.argv[1] -> your_file

sys.argv[2] -> number that is 2

Upvotes: 1

Turbo
Turbo

Reputation: 2561

Hackaholic's answer is pretty good. However, if you just want to redirect input from file using "< file2.py", then you can use raw_input.

Note that redirecting the input essentially means that the input is available on stdin and you can read it using raw_input. I found this example which is similar to what you are trying:

while True:
  try:
    value = raw_input()
    do_stuff(value) # next line was found 
  except (EOFError):
    break #end of file reached

Update: Even more elegant would be to use the solution provided here:

import sys

for line in sys.stdin:
    do_something()

Upvotes: 0

Related Questions