Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Benjamin DeYoung
The Python "TypeError: TextIOWrapper.write() takes exactly one argument (2
given)" occurs when we pass multiple arguments to the write()
method. To solve
the error, use the addition (+) operator to concatenate the strings in the call
to the method.
Here is an example of how the error occurs.
file_name = 'example.txt' with open(file_name, 'w', encoding='utf-8') as my_file: # ⛔️ TypeError: TextIOWrapper.write() takes exactly one argument (2 given) my_file.write('first line', '\n') my_file.write('second line', '\n') my_file.write('third line', '\n')
Notice that we separate the two strings using a comma, so we are passing 2
arguments to the write()
method, but the method takes a single string.
One way to solve the error is to use the addition (+) operator to concatenate the two strings.
file_name = 'example.txt' with open(file_name, 'w', encoding='utf-8') as my_file: my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n')
We replaced each comma with a plus +
to concatenate the two strings.
print('a' + 'b' + 'c') # 👉️ 'abc'
An alternative approach is to use a formatted string literal.
file_name = 'example.txt' first = 'first line' second = 'second line' third = 'third line' with open(file_name, 'w', encoding='utf-8') as my_file: my_file.write(f'{first}\n') my_file.write(f'{second}\n') my_file.write(f'{third}\n')
f
.Make sure to wrap expressions in curly braces - {expression}
.
The with open()
syntax takes care of automatically closing the file even if an
exception is thrown.
Alternatively, you can store the file object into a variable and manually close it.
file_name = 'example.txt' first = 'first line' second = 'second line' third = 'third line' my_file = open(file_name, 'w', encoding='utf-8') my_file.write(f'{first}\n') my_file.write(f'{second}\n') my_file.write(f'{third}\n') my_file.close()
Note that it's better to use the with open()
syntax as it automatically closes
the file after we are done.