I need to extract two blocks of text from several files and put them in separate lists using python. The first block starts from line 30, and isn't too hard to extract. The second block starts 2 lines after the first block; the issue is that the blocks can be of variable length. For example:
prj_files = [
line,
line,
etc
]
prj_files_2 = [
line,
etc
]
So I need to take all the lines between [] in the first block and put it in one list, and take the lines between [] in the second block and put it in another list. As of right now, I use:
for i, line in enumerate(prj):
if i > 29:
to start on a specific line, and then it uses a regular expression to find "]" where it breaks the for loop and records the line it ends on in cnt. Then I use another for loop to start at cnt + 2 to extract the second block. While I think this works, I feel like its super inefficient since I'm basically doing the same thing twice. Is there an obvious better method that I'm missing?
EDIT: So instead of parsing the file, I tried to use import
instead. I do think it's much simpler, but since I'm looping through some files to find all the files, I have a general variable that represents the file name. This means when I try to use the variable to import the file, I get the module doesn't exist error. So for example, my variable name is py_file
, and import
is reading it as py_file
instead of the actual path value. Is there a way to get around this?