hissroth
hissroth

Reputation: 251

How to open a file given in input in python?

I'm working on a project and for this I need to open a file. So for this I wanted to use open("my_file", "r") but the problem is that the name of the file is dynamic, it could be toto.txt or jziop.txt I no matter how the user will call it. I know in C I would just use open with the av[1] but is it possible in python ? I'm new in it so I'm learning.

Thanks

Upvotes: 0

Views: 974

Answers (2)

David Callanan
David Callanan

Reputation: 5800

If you import sys (a built-in module), you will have access to the sys.argv variable, a list holding all arguments passed into your program.

The first argument sys.argv[0] is the path to your program, so you actually want the second argument sys.argv[1]

python  my_script.py  my_file.txt
        ^~~~~~~~~~~~  ^~~~~~~~~~~
        sys.argv[0]   sys.argv[1]

Final code snippet:

import sys

assert len(sys.argv) >= 2

with open(sys.argv[1]) as f:
  data = f.read()

Upvotes: 1

Martin Gergov
Martin Gergov

Reputation: 1658

import sys
f = open(sys.argv[1], "r")
# do stuff
f.close()

This will read the first argument and place it as the filename.

Upvotes: 1

Related Questions