1
#From the sys package, i'm importing the argv
from sys import argv
#Un packaging the arguments
script, filename = argv 
#Print statements
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."
#To accept whether or not we want to continue or not
raw_input("?")

print "Opening the file..."
# I am opening the file
target = open(filename)

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."
x = "%r\n %r\n %r\n" % (line1, line2, line3)
target.write(x)
#This also works to write the files
# target.write ("%r\n%r\n%r\n" % (line1, line2, line3))

print "And finally, we close it."
target.close()

对于open(filename),我发现当我将脚本付诸实践时,我得到了相同的结果open(filename "w")

那么“w”的意义何在?因为我已经有了使用 target.write() 命令编写的函数!

4

2 回答 2

6

"w" 模式如果文件不存在则创建文件,如果存在则清空它。

于 2013-07-14T23:08:54.083 回答
4

根据文档open()

最常用的模式值是 'r' 用于读取,'w' 用于写入(如果文件已经存在则截断文件)和 'a' 用于附加(在某些 Unix 系统上,这意味着所有写入都附加到末尾无论当前的搜索位置如何,文件的位置)。如果省略 mode,则默认为 'r'。

于 2013-07-14T23:07:48.763 回答