TextIOWrapper.write() takes exactly one argument (2 given)

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

TextIOWrapper.write() takes exactly one argument (2 given) #

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.

typeerror textiowrapper write takes exactly one argument 2 given

Here is an example of how the error occurs.

main.py
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.

main.py
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.

main.py
print('a' + 'b' + 'c') # 👉️ 'abc'

An alternative approach is to use a formatted string literal.

main.py
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')
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with 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.

main.py
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.