Noorul Noorul - 3 months ago 13x
Python Question

How to read first N lines of a text file and write it to another text file?

Here is the code I modified from previous code.
But, I got this error:

TypeError: must be str not list in f1.write(head)

This is the part of code that is producing this error:

from itertools import islice
with open("input.txt") as myfile:
head = list(islice(myfile, 3))


Jim Jim

Well, you have it right, using islice(filename, n) will get you the first n lines of file filename. The problem here is when you try and write these lines to another file.

The error is pretty intuitive (I've added the full error one receives in this case):

TypeError: write() argument must be str, not list

This is because f.write() accepts strings as parameters, not list types.

So, instead of dumping the list as is, write the contents of it in your other file using a for loop:

with open("input.txt", "r") as myfile:
    head = list(islice(myfile, 3))

# always remember, use files in a with statement
with open("output.txt", "w") as f2:
    for item in head:

Granted that the contents of the list are all of type str this works like a charm; if not, you just need to wrap each item in the for loop in an str() call to make sure it is converted to a string.

If you want an approach that doesn't require a loop, you could always consider using f.writelines() instead of f.write() (and, take a look at Jon's comment for another tip with writelines).