Skip to content
Advertisement

getting TypeError: write() argument must be str, not list when trying to add text from 1 file to another

I got 2 text files with lists text1.txt

Pig
Goat
Duck
Cow
Chicken
Sheep
Horse

and text2.txt

Lydia
Marie
Mike

What I want to do is add the text of file 1 after the second line of file 2 like this:

Lydia
Marie
Pig ---> list will be added here
Goat
Duck
Cow
Chicken
Sheep
Horse
Mike ---> old list continues

I wrote a the following script as suggested on this site:

with open("text1.txt", "r") as f1:
    t1 = f1.readlines()
with open("text2.txt", "r") as f2:
    t2 = f2.readlines()
t2.insert(2, t1)
with open("text2.txt", "w") as f2:
    f2.writelines(t2)

and getting the following error:

    f2.writelines(t2)
TypeError: write() argument must be str, not list

Advertisement

Answer

When you do

t2.insert(2, t1)

you’re creating a nested list. t2 looks like

["Lydia", "Marie", ["Pig", "Goat", "Duck", ...], "Mike"]

writelines() expects a flat list of strings, when it gets to the nested list it can’t write it.

If you want to splice into the list rather than inserting a nested list, use a slice assignment.

t2[2:2] = t1
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement