5

I am learning python and I wrote a script that copies the content of one text file to another.

Here is my code.

from sys import argv
out_file = open(argv[2], 'w').write(open(argv[1]).read())
out_file.close()

I get the AttributeError listed on the title. Why is it that wen I call the write method on open(argv[2], 'w') the out_file is not assigned a File type?

Thank you in advance

Biscuits
  • 63
  • 1
  • 1
  • 3

2 Answers2

5

out_file is being assigned to the return value of the write method, which is None. Break the statement into two:

out_file = open(argv[2], 'w')
out_file.write(open(argv[1]).read())
out_file.close()

And really, it'd be preferable to do this:

with open(argv[1]) as in_file, open(argv[2], 'w') as out_file:
    out_file.write(in_file.read())

Using with with statement means Python will automatically close in_file and out_file when execution leaves the with block.

dano
  • 91,354
  • 19
  • 222
  • 219
  • Thank you for your answer I had originally coded it like your first example but I was trying to get it as short as possible. The with statement looks interesting I will look more into it. – Biscuits Jul 26 '14 at 17:46
2

out_file is bound to the return value of write(); it returns None.

The expression open(...).write(...) calls the write method on the open file object but the open file object itself is then discarded again after the expression completes. While the expression is executed only the stack is referencing it.

You want to use the file object as a context manager instead, and it'll be closed automatically:

with open(argv[2], 'w') as writefile, open(argv[1]) as readfile:
    writefile.write(readfile.read())

The with .. as .. statement has also bound just the open file objects to names, so you can now address those objects directly.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343