. Advertisement .
..3..
. Advertisement .
..4..
This article will answer how to resolve the “TypeError: write() argument must be str, not list” when adding the text from one file to another file in Python. This is among the most common issues that users will face. Thus, why would it occur or how can it be corrected? We’ll go through it with you now. Check it out!
How does the “TypeError: write() argument must be str, not list” error occur?
You had two wording files with the lists of text1.txt as below:
Pig
Goat
Duck
Cow
Chicken
Sheep
Horse
The second file of text2.txt here:
Lydia
Marie
Mike
Above are the two files that you want to add or merge from the first file behind the second word in file two. Here is an example for what you want to insert as follow:
Lydia
Marie
Pig ---> list will be added here
Goat
Duck
Cow
Chicken
Sheep
Horse
Mike ---> old list continues
To do it, you run this code:
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)
After that, you found the following warning message:
f2.writelines(t2)
TypeError: write() argument must be str, not list
What causes error?
This occurs when you try to add the text from the original to another file in Python. writelines()
expects a simple list of strings and when it reaches the nested list, it won’t write it. This is something that may easily occur by mistake and let’s see what it is solve in detail.
How to solve this problem
1. Using insert()
To append, you can use insert() instead of writelines(). The function syntax is as follows:
t2.insert(2, t1)
and File t2 should become like this:
["Lydia", "Marie", ["Pig", "Goat", "Duck", ...], "Mike"]
In addition, if you wish to connect to the list instead of adding an embedded list, use the assignment of slice as follow:
t2[2:2] = t1
2. Using f.write(str(a))
For example, you have data a. First of all, convert the data to string:
str(a)
Then use the following syntax:
f.write(str(a))
Conclusion
Was our solution on “TypeError: write() argument must be str, not list” has supported you a lot for your problem? If so, you may provide us with your thoughts and ideas in the comment box below to understand your problem better. Moreover, if you have any concerns during your work, feel free to chat with us for more support to find out which solution may best suit you. Wishing you a good day ahead!
Leave a comment