python - 为什么 out_file = open(to_file, 'w') 和 out_file.write(in_data) 都是必要的?
问题描述
所以我正在用Learn Python The Hard way这本书学习python,我正在练习17。这是代码:
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)
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()
我的问题是为什么这两行都是必要的。我明白为什么使用第一行但第二行第二行呢。对我来说,如果我们删除第二行,代码理论上应该以相同的方式工作。有人可以帮我理解这一点吗?out_file = open(to_file, 'w') out_file.write(indata)
解决方案
第二行基本上覆盖了文件(to_file)的内容,因为操作模式是写模式,或者如果它不存在则创建一个新文件。这里的 out_file 是一个文件对象,您可以通过它执行文件操作。根据您的作业目标猜测,您基本上是在复制(写入)到另一个文件,这就是提到第二行的原因。
您还可以遵循另一个变体-
with open(to_file,'w') as out_file:
```out_file.write(indata)
the latter will automatically close the file object, thereby preventing any errors
推荐阅读
- ios - 缩放上的核心绘图小刻度标签
- magento - Magento 1.9:排序网格视图
- sqlite - Haskell HDBC.Sqlite3 fetchAllRows
- sendgrid - Custom_args 在 sendgrid V3 API 中不起作用,但 unique_args 发送电子邮件但在 event_callback 中不起作用
- python - 在 Python 中动态循环 json 数据
- java - 谷歌地方 API 密钥
- reverse - 当我从内存中转储一个pe时,我该如何修复IAT?
- sql - 遍历所有表
- mongoose - 不区分大小写的键名匹配,Mongoose
- apache - Chrome 允许不安全的本地主机标志不适用于虚拟主机