0

I'm trying to put together a file that accepts inputs from a user as to a number of text files they want analyzed. As a first step, I want to just take the contents of each document they input (can be any number, no limit) and record the contents of each line of the document as an item in a list. I'd like to have a separate list for each document that the user inputs, but that is where I'm struggling. Below is what I've got so far.

def user_input():
    prompt = raw_input("Please input the full name (e.g. text_file.txt) or path of a text file:")
    global lst
    lst = {}
    lst[0] = prompt
    global file_count
    file_count = 1
    while len(prompt) > 0:
        prompt = raw_input("Please input any additional text files or simply press enter to continue:")
        if len(prompt) > 0:
            lst[file_count] = prompt
            file_count = file_count+1
    return lst

def read_in():
    for x in lst.values():
        file = open(x)
        x = file.readlines()

I'm stuck at this part now as I'm not sure how to dynamically assign names to each list. Any help would be greatly appreciated!!

2
  • 4
    Whenever you think you need dynamic variables, use a dictionary instead. somedict[name] = somelist is always going to be easier than trying to figure out how to set new variables dynamically. Commented Feb 14, 2013 at 8:31
  • 2
    Defining lst and file_count as global variables seems unnecessary. Commented Feb 14, 2013 at 8:33

1 Answer 1

1
def get_filenames():
    filelist = []
    prompts = [
        "Please input the full name (e.g. text_file.txt) or path of a text file:",
        "Please input any additional text files or simply press enter to continue:"
    ]
    while True:
        filename = raw_input(prompts[len(filelist) > 0]).strip()
        if not filename:
            break
        filelist.append(filename)
    return filelist

def get_filelines(filelist):
    files = {}
    for filename in filelist:
        with open(filename, 'rb') as fp:
            files[filename] = fp.readlines()
    return files

if __name__=='__main__':
    print get_filelines(get_filenames())
Sign up to request clarification or add additional context in comments.

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.