I got 2 text files with lists text1.txt
JavaScript
x
8
1
Pig
2
Goat
3
Duck
4
Cow
5
Chicken
6
Sheep
7
Horse
8
and text2.txt
JavaScript
1
4
1
Lydia
2
Marie
3
Mike
4
What I want to do is add the text of file 1 after the second line of file 2 like this:
JavaScript
1
11
11
1
Lydia
2
Marie
3
Pig ---> list will be added here
4
Goat
5
Duck
6
Cow
7
Chicken
8
Sheep
9
Horse
10
Mike ---> old list continues
11
I wrote a the following script as suggested on this site:
JavaScript
1
8
1
with open("text1.txt", "r") as f1:
2
t1 = f1.readlines()
3
with open("text2.txt", "r") as f2:
4
t2 = f2.readlines()
5
t2.insert(2, t1)
6
with open("text2.txt", "w") as f2:
7
f2.writelines(t2)
8
and getting the following error:
JavaScript
1
3
1
f2.writelines(t2)
2
TypeError: write() argument must be str, not list
3
Advertisement
Answer
When you do
JavaScript
1
2
1
t2.insert(2, t1)
2
you’re creating a nested list. t2
looks like
JavaScript
1
2
1
["Lydia", "Marie", ["Pig", "Goat", "Duck", ], "Mike"]
2
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.
JavaScript
1
2
1
t2[2:2] = t1
2