Newbie: python len () closes file?

I am new to Python and am looking at Zed's book. I came across the following exercise, the scope of which is to copy one txt to another.

The source code from the book works fine, and I copy below - so that I can show the difference:

1 from sys import argv
2 from os.path import exists
3
4 script, from_file, to_file = argv
5
6 print "Copying from %s to %s" % (from_file, to_file)
7
8 # we could do these two on one line too, how?
9 in_file = open(from_file)
10 indata = in_file.read()
11
12 print "The input file is %d bytes long" % len(indata)
13
14 print "Does the output file exist? %r" % exists(to_file)
15 print "Ready, hit RETURN to continue, CTRL- C to abort."
16 raw_input()
17
18 out_file = open(to_file, 'w')
19 out_file.write(indata)
20
21 print "Alright, all done."
22
23 out_file.close()
24 in_file.close()

What I decided to do was to avoid having the variable in_file and indata strong>, so I made some changes on lines 9-10, 12 and 19 and wrote the following code:

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

# we could do these two on one line too, how?
in_file = open(from_file)


print "The input file is %d bytes long" % len(in_file.read())

print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL- C to abort."
raw_input()

out_file = open(to_file, 'w')
out_file.write(in_file.read())

print "Alright, all done."

out_file.close()
in_file.close()

My problem:

1) As the modified code is written , althouhg correctly displays in_file.read () bytes, it never copies text from from_file to to_file

2) , , len() - .

, len(), in_file.

, ? , in_file = open (from_file)? ?

, :)

+4
1

in_file.read(), . , , :

indata = in_file.read()

, in_file.read(), "" . , , , . , , . in_file.read() , , - , .

- , " " , @WayneWerner .

in_file.seek(0)
+2

Source: https://habr.com/ru/post/1656004/


All Articles