2011-08-29 64 views
0

我正在努力通過學習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」嗎?

這可能相當於被孩子問及保持天空或某物的東西,我爲某種厚重道歉。謝謝!

+2

你能在「不工作」詳細點嗎?你有例外嗎?如果是這樣,請提供。如果沒有,請解釋你的期望以及你實際收到的內容。 –

+0

這種方式失敗了嗎? –

+1

而我錯過了機會,我可以猜測它 - 有可能是當你重新打開文件來驗證它的內容時,你正在使用的編輯器不能識別'\ n'作爲換行符,並且它在事實上尋找'\ r \ n'(回車+換行)?例如,這在Windows的記事本中很常見。 –

回答

9
target.write("%s %s %s %s %s %s") % (line1, linebreak, line2, linebreak, line3, linebreak) 

應該

target.write("%s %s %s %s %s %s" % (line1, linebreak, line2, linebreak, line3, linebreak)) 

,但會更好的寫法如下:

target.write(' '.join(line1, linebreak, line2, linebreak, line3, linebreak)) 
+0

或'target.write(linebreak.join([line1,line2,line3]))'' – 2011-08-29 17:49:42

7

假設你得到

TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple' 

你需要的是

target.write("%s %s %s %s %s %s" % (line1, linebreak, line2, linebreak, line3, linebreak)) 

也就是說,你需要使用%運營商的字符串,而不是對target.write()結果。如果您知道target.write()返回None,則該錯誤消息可能對您更有意義,其類型爲NoneType

0

我沒有這個幾天前,在練習22,他會問你的一切寫下來你到目前爲止已經學習並記住它。

早些時候,他要求你評論每一行以解釋它的作用。這可能是一個非常好的習慣,除非你知道線條的作用而不必考慮它們。

還要小心你如何陳述事情。

如果你想成爲一名程序員,你需要開始像一個人說話,並使用詞彙。

line1,line2,line3,linebreak被稱爲變量。您可以使用=(賦值運算符)臨時給他們/賦值。

寫是一個函數。 Python中的函數在()之間帶參數。 參數的所有必須適合在()內。如果你這樣寫的話,我相信它不會讓你失望。

stuffIWantToPrint = line1 + lb + line2 + lb+ line3 + lb #all strings together 
target.write(stuffIWantToPrint) #pass the big string to write 
0

我很遲,但你也這樣做: target.write("{line1}\n{line2}\n{line3}\n").format(line1=line1,line2=line2,line3=line3)