2

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)) f1.write(head) f1.close() 
1
  • where did you declare Commented Nov 25, 2015 at 3:28

1 Answer 1

5

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: f2.write(item) 

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

Sign up to request clarification or add additional context in comments.

1 Comment

Note: you've mis-spelt islice (first example) - and instead of creating a list, then using: f2.writelines(islice(myfile, 3)) will work fine...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.