Miyek
Miyek

Reputation: 1

Python: Print specific range of line from text file

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..

Upvotes: 0

Views: 1371

Answers (1)

PseudoAj
PseudoAj

Reputation: 5931

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.

Upvotes: 1

Related Questions