0

I have a directory with numerous subdirectories.

At the bottom of the directories there are some .txt files i need to extract line 2 from.

import os
import os.path
import linecache

for dirpath, dirnames, filenames in os.walk("."):
    for filename in [f for f in filenames if f.endswith(".txt")]:
        #print os.path.join(dirpath, filename)
        #print filename
        print linecache.getline(filename, 2)

I am able to successfully parse all the directories and find every text file. But linecache.getline simply returns newline (where there should be data from that line of the files). Using

print linecache.getline(filename, 2).rstrip('\n') 

Does not solve this either.

I am able to correctly print out just the filenames in each directory, but passing these to linecache seems to potentially be the issue. I am able to use linecache.getline(file, lineno.) successfully if I just run the script on 1 .txt file in the current directory.

cc6g11
  • 477
  • 2
  • 10
  • 24

1 Answers1

1

linecache.getline takes filename from current working directory.

Solution is thus:

import os
import os.path
import linecache

for dirpath, dirnames, filenames in os.walk("."):
    for filename in [f for f in filenames if f.endswith(".txt")]:
        direc = os.path.join(dirpath, filename)
        print linecache.getline(direc, 2)
cc6g11
  • 477
  • 2
  • 10
  • 24