初学者:python len()关闭文件?

我是
Python的新手并经历了Zed的书.我偶然发现了以下练习,其范围是将一个txt复制到另一个.

书中的原始代码完美无缺,我在下面复制 – 这样我就可以显示出差异:

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()

我决定做的是避免使用变量in_file和indata,所以我在9-10,12和19行做了一些更改并编写了以下代码:

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()

我的问题是:

1)编写修改后的代码,但是它正确打印了in_file.read()的字节,它从不将文本从from_file复制到to_file

2)如果在修改中我只省略了计算字节的行 – 所以len()函数 – 那么它通常将一个文件复制到另一个文件.

根据我的理解,通过唤起len()函数,然后关闭in_file.

我的想法是否正确?我可以通过不必重复代码in_file = open(from_file)来避免这种情况吗?还有什么可能的原因?

我很感激帮助,因为这让我有点疯狂:)

最佳答案 它实际上是两次调用in_file.read()的行为导致你的问题.您可以通过将结果分配给变量来修复它,如原始中所示:

indata = in_file.read()

原因是当你调用in_file.read()时,你“耗尽”了文件.将文件想象成一本书 – 当计算机读取它时,它会留下一个书签,它会离开.所以当它完成后,书签就会留在书的最后一页.当你第二次调用in_file.read()时,python从书签剩下的地方开始 – 最后,没有剩下的页面可供阅读.

如果由于某种原因想要避免创建变量,可以将“书签”移回文件的开头,如@WayneWerner在评论中所建议的那样.

in_file.seek(0)
点赞