My task is to search the 3rd column of each file for some target words and every time a target word is found in the corpus the 10 words before and after this word have to be added to a multidimensional dictionary.

EDIT: The lines containing a '&', a '\' or the string '(unknown)' should be excluded.

I tried to solve this using readlines() and enumerate() as you see in the code below. The code does what it should but it is obviously not efficient enough for the amount of data provided in the source file.

I know that readlines() or read() should not be used for huge data sets as it loads the whole file into memory. Nevertheless, reading the file line by line, I did not manage to use the enumerate method to get the 10 words before and after the target word.
I also cannot use mmap as I do not have the permission to use it on that file.

So, I guess the readlines method with some size limitation would be the most efficient solution. However, going for that, would I not make some errors as each time reaching the end of the size limit the 10 words after the target word would not be captured as the code just breaks?

targets_dict = get_target_to_dict('targets_uniq.txt')
# browse directory and process each file
# find the target words to include the 10 words before and after to the dictionary
# exclude lines starting with <,-,; to just have raw text

I copied the whole part of the code for reasons of completeness as it is all part of one function which creates a multidimensional dictionary out of all information extracted and writes it to a csv file then.

I would really appreciate any hint or suggestion to make this code more efficient.

EDIT I corrected the code, so that it takes into account the exact 10 words before and after the target word

my idea was to create a buffer to store before 10 lines and another buffer to store after 10 lines, as the file being read, it will be push into before buffer and the buffer will be pop off if size exceed 10

for the after buffer, i clone another iterator from the file iterator 1st. Then running both iterator in parallel within the loop with clone iterator running 10 iteration ahead to get the after 10 lines.

This avoid using readlines() and load whole file in memory.
Hope it works for you in actual case

edited:
only fill the before after buffer if column 3 does not contains any of '&', '\', '(unknown)'.Also change split('\t') into just split() so it will take care all whitespace or tab