0

I have several text files in a directory. In every text file, they have these lines

***************Error Summary**********************

line 1

line 2

line n

====================================

Every text file doesn't have equal number of lines (n). For example file1 have 3 lines, file2 have 1 line and so on. What I have to do is print from line 1 until line n in a list. Every file have their own list.

This is my first code

target = "Error Summary"

for file in files: 
    content = open(os.path.join(subdir, file),'r')
    for line in content:
    if target in line:
        chunk = ''.join(islice(content,50))
        chunk = chunk.split("==", 1)[0]
        chunk_list.append(chunk)

But these will disturb my next code as the pointer already go to line 51. So I come out with the new code

for line in content:
    if target in line:
        for i in range(50):
            chunk = content.next()
            if chunk.startswith("=="):
                break
            chunck_list.append(chunk)

This looks nice. However, all the line is printed in one list. Anyone can help?

---------------------------EDIT-----------------------------

I got the code already

for line in content:
   if target in line:
      for line in content:
         if line.startswith("=="):
            break
         chunk_list.append(line)

But the output is compressed in one list. What I want is output of File1 in list1, output of File2 in list2, and so on. Anyone please help me..

Miyek
  • 1
  • 2

1 Answers1

1

I would suggest using linecache. Here is the documentation for the library. You do something like:

>>> import linecache
>>> linecache.getline(FILENAME, LINENUMBER)

It would be handy to have files in memory but remember if you have a million files to read, this wouldn't scale.

PseudoAj
  • 5,234
  • 2
  • 17
  • 37
  • This works if we know the number of lines. In my case, the text file have hundreds of line and the target might be on the top side of file 1, bottom side of file 2, and at the middle of file 3. Any idea? – Miyek Mar 06 '17 at 02:51
  • You can get the count of lines for files using: http://stackoverflow.com/questions/845058/how-to-get-line-count-cheaply-in-python – PseudoAj Mar 06 '17 at 03:19