Finding the length of a certain part of a list

Question:

I am trying to figure out how to find the length of a certain part of a list. For example, my program has a usernames, and passwords in my config file. Is there a way to figure out how many usernames there are? And if so then how?

#Also any of the spaces you see between the words are just for reading's sake
#and won't be there in the final program

firsttime:
True

Username:
user1
user2

Password:
pass1
pass2

Key:
key

Theme:
#303030
white
Asked By: Astro

||

Answers:

If we suppose that your configuration lines are stored in a file called my_conf.cfg, we can try to code a custom parser like this:

with open('(...)/my_conf.cfg') as cf:
    _con_lines = cf.readlines()

configuration = {}
for c_l in _con_lines:
    c_l.strip('n')
    if not c_l or c_l.startswith('#'):
    
        continue
    if c_l.endswith(':'):
        key = c_l[:-1]
        configuration[key] = []
    else:
        configuration[key].append(c_l)

Then the answer to your question is

len(configuration['Username'])
Answered By: Francesco Pinna

Very late to responding to my own post but I made my own parser of sorts which works very well in my opinion.

# dictionary.txt can be replaced with any file

def gettext(header, move, count):
    with open('dictionary.txt', 'r') as f:
        f = f.read()
        lines = f.split("n")

    for i, line in enumerate(lines):
        if header in line:
            word = []
            for l in range(0, count):
                newindex = i + move
                word.append(lines[newindex+l])

            return "n".join(word)

This works well for any file format like the one I had. The header variable is the header you are looking for and then looks for the string then. You can even join together multiple lines together with the count variable and the move is used to look x lines down to then grab the string.

Answered By: Astro
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.