I have a directory with 260+ text files containing scoring information. I want to create a summary text file of all of these files containing filename and the first two lines of each file. My idea was to create two lists separately and ‘zip’ them. However, I can get the list of the filenames but I can’t get the first two lines of the file into an a appended list. Here is my code so far:
# creating a list of filename
for f in os.listdir("../scores"):
(pdb, extension) = os.path.splitext(f)
name.append(pdb[1:5])
# creating a list of the first two lines of each file
for f in os.listdir("../scores"):
for line in open(f):
score.append(line)
b = f.nextline()
score.append(b)
I get an error the str had no attribute nextline. Please help, thanks in advance.
The problem you’re getting is a result of trying to take more than one line at a time from the scores file using a file iterator (
for line in f). Here’s a quick fix (one of several ways to do it, I’m sure):The
withstatement takes care of closing the file for you after you’re done, and it gives you a filehandle object (fh), which you can grab lines from manually.