Search code examples
pythonlistreadfilelines

how can I print lines of a file that specefied by a list of numbers Python?


I open a dictionary and pull specific lines the lines will be specified using a list and at the end i need to print a complete sentence in one line.

I want to open a dictionary that has a word in each line then print a sentence in one line with a space between the words:

N = ['19','85','45','14']
file = open("DICTIONARY", "r") 
my_sentence = #?????????

print my_sentence

Solution

  • If your DICTIONARY is not too big (i.e. can fit your memory):

    N = [19,85,45,14]
    
    with open("DICTIONARY", "r") as f:
        words = f.readlines()
    
    my_sentence = " ".join([words[i].strip() for i in N])
    

    EDIT: A small clarification, the original post didn't use space to join the words, I've changed the code to include it. You can also use ",".join(...) if you need to separate the words by a comma, or any other separator you might need. Also, keep in mind that this code uses zero-based line index so the first line of your DICTIONARY would be 0, the second would be 1, etc.

    UPDATE:: If your dictionary is too big for your memory, or you just want to consume as little memory as possible (if that's the case, why would you go for Python in the first place? ;)) you can only 'extract' the words you're interested in:

    N = [19, 85, 45, 14]
    
    words = {}
    word_indexes = set(N)
    counter = 0
    with open("DICTIONARY", "r") as f:
        for line in f:
            if counter in word_indexes:
                words[counter] = line.strip()
            counter += 1
    
    my_sentence = " ".join([words[i] for i in N])