LPTHW - Ex17 - unexpected object type

Hello there, I’m trying to figure out something funky happening when I try to shorten the example code as per study drill. This is the shortened variant:

from sys import argv

script, from_file, to_file = argv

indata = open(from_file).read()

out_file = open(to_file, 'w').write(indata)
print(type(out_file))
print(out_file)

this works fine, but as it turns out, “out_file” is an integer, with the value of len(indata), which surprised me, since I expected a textIOwrapper object:

<class ‘int’>
6

if I rewrite the code to this:

out_file = open(to_file, 'w')
print(type(out_file))
print(out_file)
out_file.write(indata)
print(type(out_file))
print(out_file)

I get, as I’d expected (apart from working code):

<class ‘_io.TextIOWrapper’>
<_io.TextIOWrapper name=‘testto.txt’ mode=‘w’ encoding=‘cp1252’>
<class ‘_io.TextIOWrapper’>
<_io.TextIOWrapper name=‘testto.txt’ mode=‘w’ encoding=‘cp1252’>

could someone please explain what is happening? Thanks in advance.

out_file = open(to_file, 'w').write(indata)

could be unfolded to

out_file = open(to_file, 'w')
result = out_file.write(indata)

In your shorthand out_file is bound to the return value of write called on the opened file (same as result in my version) and that’s the number of characters written to the file.

Thanks for the explaination!