我正在努力通過學習Python艱難的方式,並試圖瞭解它而不是隻是錘掉。我被困在練習16中,已經討論了所以在這裏:總Python Noob:爲什麼這不工作?
Very basic Python question (strings, formats and escapes)
但我仍然試圖找出爲什麼這個方法行不通:
from sys import argv
script, filename = argv
print "Attempting to open the file now."
print open(filename).read()
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-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."
linebreak = "\n"
target.write("%s %s %s %s %s %s") % (line1, linebreak, line2, linebreak, line3, linebreak)
target.write("the ending line")
print "And finally, we close it."
target.close()
我已經建立一個換行值,並且在target.write命令中使用%s調用line1,line2和linebreak值。在閱讀時它不應該解析爲「line1 \ n line2 \ n line3 \ n」嗎?
這可能相當於被孩子問及保持天空或某物的東西,我爲某種厚重道歉。謝謝!
你能在「不工作」詳細點嗎?你有例外嗎?如果是這樣,請提供。如果沒有,請解釋你的期望以及你實際收到的內容。 –
這種方式失敗了嗎? –
而我錯過了機會,我可以猜測它 - 有可能是當你重新打開文件來驗證它的內容時,你正在使用的編輯器不能識別'\ n'作爲換行符,並且它在事實上尋找'\ r \ n'(回車+換行)?例如,這在Windows的記事本中很常見。 –