# 习题 16: 读写文件¶

• close – 关闭文件。跟你编辑器的 文件->保存.. 一个意思。
• truncate – 清空文件，请小心使用该命令。
• write(stuff) – 将stuff写入文件。

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33``` ```from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." target = open(filename, 'w') print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "I'm going to write these to the file." target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print "And finally, we close it." target.close() ```

## 你应该看到的结果¶

```\$ python ex16.py test.txt
We're going to erase 'test.txt'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file.  Goodbye!
Now I'm going to ask you for three lines.
line 1: To all the people out there.
line 2: I say I don't like my hair.
line 3: I need to shave it off.
I'm going to write these to the file.
And finally, we close it.
\$
```

## 加分习题¶

1. 如果你觉得自己没有弄懂的话，用我们的老办法，在每一行之前加上注解，为自己理清思路。就算不能理清思路，你也可以知道自己究竟具体哪里没弄明白。
3. 文件中重复的地方太多了。试着用一个 target.write()line1, line2, line3 打印出来，你可以使用字符串、格式化字符、以及转义字符。
4. 找出为什么我们需要给 open 多赋予一个 'w' 参数。提示： open 对于文件的写入操作态度是安全第一，所以你只有特别指定以后，它才会进行写入操作。
5. 如果你用 'w' 模式打开文件，那么你是不是还要 target.truncate() 呢？阅读以下 Python 的 open 函数的文档找找答案。

'w' 是什么意思？