建议ex15-17连起来学习
知识点: write
如果你做了上一节的study drills,你应该看到对文件,我们有各种各样的方法进行操作。下面的列表希望你记住的
close:关闭文件
read:读取文件内容
readline:只读取一行内容
truncate:清空文件。如果你的文件很重要,使用时注意
write(‘stuff’):往文件里写东西
seek(0):把光标移动到文件开始处
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
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 = input("Line 1: ")
line2 = input("Line 2: ")
line3 = 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()
What you should see
(venv) C:\Users\PycharmProjects\learnpythonthehardway>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: Mary had a little lamb
Line 2: Its fleece was white as snow
Line 3: It was also tasty
I'm going to write these to the file.
And finally, we close it.
Study Drills
1、如果不懂,就一行行注释,这是最有效的方法。
2、写一个跟上一节差不多的脚本,来读取刚刚创建的文件
3、试试用一行代码来取代25-30行,还是用target.write()
4、第12行,我们为什么要给 open 加参数 ‘w’ ?
5、既然用了参数 ‘w’ ,我们还需要用上 target.truncate()这个方法吗?