2013-07-14 23 views
0
#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")在python中使用「w」模式有什麼意義?

什麼是「W」,然後點?由於我已經有了一個函數來寫入target.write()命令!

+4

備註:使用'with open(filename)作爲目標:'而不是手動關閉。這確保了異常安全。參見[PEP 343](http://www.python.org/dev/peps/pep-0343/)。 – 2013-07-14 23:05:46

回答

3

根據​​:

的模式最常用的值是「R」讀,寫(截斷如果它已經存在的文件),「W」和「A」的追加(在某些Unix系統上,這意味着無論當前的查找位置如何,所有寫操作都會追加到文件末尾)。如果省略模式,則默認爲'r'。

4

「w」模式創建文件,如果它不存在,並清空它,如果它。

相關問題