0

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

9
  • What do you mean by "the name of the file is dynamic"? Commented Aug 4, 2019 at 14:06
  • 7
    Use sys.argv[1]. Command line arguments can be accessed from sts.argv[] array. Commented Aug 4, 2019 at 14:06
  • It's not always the same name, the user can input a .txt file with a total random name. Commented Aug 4, 2019 at 14:06
  • 1
    you already have the answer from comments fname = sys.argv[1] - just use it Commented Aug 4, 2019 at 14:08
  • open() can be passed a string variable Commented Aug 4, 2019 at 14:08

2 Answers 2

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

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

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

3 Comments

Personally i wouldn't still a code from the comments.
Let's show some dignity and not post a ready answers from comments
@u Isn't good that some actually writes some answer that can be voted up or down? The answer could be improved with an explanation or reference but at least it is complete.
1

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()

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.