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()よると:

mode の最も一般的に使用される値は、読み取り用の 'r'、書き込み用の 'w' (ファイルが既に存在する場合はファイルを切り捨てる)、および追加用の 'a' (一部の Unix システムでは、すべての書き込みが末尾に追加されることを意味します) です。現在のシーク位置に関係なく、ファイルの モードが省略された場合、デフォルトは 'r' になります。

于 2013-07-14T23:07:48.763 に答える