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."
#write 需要接收一个字符串作为参数,从而将该字符串写入文件
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()
Note: 自己定义filename,会生成以其命名的文件,并且在里面写入内容。
truncate() 方法用于截断文件,如果指定了可选参数 size,则表示截断文件为 size 个字符。 如果没有指定 size,则从当前位置起截断;截断之后 size 后面的所有字符被删除。
作者告诉我们应该记住的几个命令:
你应该记住的命令如下:
• close – 关闭文件。跟你编辑器的 文件 -> 保存.. 一个意思。
• read – 读取文件内容。你可以把结果赋给一个变量。
• readline – 读取文本文件中的一行。
• truncate – 清空文件,请小心使用该命令。
• write(stuff) – 将 stuff 写入文件。