1

I am looking to set a text file rand.letter.txt as the default word file in this argparse segment, to be used and read in the program. I would assume this should be situated in row 4-5 down below. How should I do this?

As you will see I have already done that with the matrix size. But I am struggling when in regards of a file with str characteristics.

def main():
    print("WELCOME TO THE MEMORY PUZZLE!")

    parser = argparse.ArgumentParser(description="Memory game") 
    parser.add_argument("words_file", metavar="FILE", nargs=1,
                        help="Words file")

    parser.add_argument(
        "--matrix-size",
        metavar="SIZE",
        dest="matrix_size",
        help="Matrix size",
        default=6,
        type=int,
        )

    args = parser.parse_args()

    game = Game(args.words_file[0], args.matrix_size)
    game.play()

Thank you so much for any help or input!

Tomalak
  • 332,285
  • 67
  • 532
  • 628
Becky8
  • 25
  • 4
  • 1
    Have you tried adding `default="rand.letter.txt"`? – Jasmijn Dec 07 '20 at 09:36
  • Yes, unfortunately its does not work, returns that it is missing a file if I dont include one when i start the program (which I am looking to not have to do), "error: the following arguments are required: FILE" – Becky8 Dec 07 '20 at 09:40

2 Answers2

0

If you want a default postional argument you need to specify the nargs as ?. This will consume one argument from the command line, if available, otherwise the default will be used.

parser.add_argument(
    "words_file", nargs="?", default="rand.letter.txt", help="Words file"
)

Also, when you initialise your game you are slicing the first character off the words_file variable. You need to change it to:

game = Game(args.words_file, args.matrix_size)

Notice the [0] is gone.

Alex
  • 6,610
  • 3
  • 20
  • 38
  • Thank you, the issue is that I get this message: " FileNotFoundError: [Errno 2] No such file or directory: 'r' " When I dont type in any argument (since I just want the defaults): (venv) n147-p63:Project rebeckae$ python3 game.py – Becky8 Dec 07 '20 at 10:12
0

If you want to set default values for positional, you have to specify nargs="?" Source. nargs=1 seems to be superfluous in your example anyways, since it only produces a list of one item. So your line should look like this:

parser.add_argument("words_file", metavar="FILE", nargs="?",
                        default="rand.letter.txt", help="Words file")
Cloudtower
  • 11
  • 1