Python Forum

Full Version: help me with this code : (
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import sys
import os
import random

exam = sys.argv[1]
folder = sys.argv[2]

questions = []
for bank, number in zip(sys.argv[3::2], map(int, sys.argv[4::2])):
    qfiles = [
        os.path.join(dirpath, fname) 
        for dirpath, dirnames, filenames in os.walk(os.path.join(folder, bank)) 
        for fname in filenames 
        if os.path.splitext(fname)[-1].lower() == '.tex'
        ]
    for qfile in random.sample(qfiles, number):
        with open(qfile, 'r') as qfh:
            questions.append(qfh.read())

with open(exam, 'w') as efh:
    for question in questions:
        print(question, file=efh)
Reference: https://tex.stackexchange.com/questions/...710#499710

everytime I try to run it, it tells me index error or population size too large/negative.

Any advice or guidance will be greatly appreciated :)
The problem you are having is not clear. Please post the full text of any error message you receive.
Traceback (most recent call last):
File "C:/Users/Admin/Desktop/exams/script.py", line 5, in <module>
exam = sys.argv[1]
IndexError: list index out of range.

When I run it from python idele.
Well, that's not a problem with the program. You are just not providing it with the command line arguments it needs.

You have a couple open ended slices there, so it seems like you could have a long list of command line arguments. That does not strike me as a good way to get data into the program. I would rewrite all of this as a function, that could take exam, folder, and a file name as parameters, and then read the open ended stuff (the exam questions?) from the file. Then call the function with the appropriate parameters.