2012-09-07 52 views
-3

看到最後四行:「這裏的更新文件」Python:爲什麼我的代碼不打印?

from sys import argv 

script, filename = argv 
print "we're going to erase %r." % filename 

txt = open(filename) 
print txt.read() 
print "If you do not want that, hit CTRL-C (^C)." 
print "If you do want that, hit RETURN." 
raw_input("?") 
print "Opening the file..." 
target = open(filename, 'w') 
print "Truncating the file. Good bye!" 
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." 
target.write("%s\n%s\n%s\n" % (line1, line2, line3)) 
target.close() #Need to close the file when done editing, or else cant open. 

print "Here's the updated file!" 
txt = open(filename) 
print txt.read() 

我想顯示在命令提示符下更新的文件,但它不打印,打印的最後一行說:更新的文件在哪裏?!?!

更新:我得到它的工作,我忘了包括一行「目標=打開(文件名,'W')」,我試圖通過刪除我的意見,使眼睛更容易,但是,我意外刪除這個重要的peice。它現在正在打印我想要的內容。感謝您的幫助,我不確定爲什麼現在工作。

+2

該腳本有問題。例如,「target」分配給了哪裏? – 2012-09-07 18:29:21

+9

你沒有發佈你正在運行的代碼。如果你運行這個代碼,你會得到一個NameError作爲'target',因爲你沒有定義任何叫做'target'的變量。 – BrenBarn

+0

如果您發佈了收到的任何錯誤消息的文本,它也會有所幫助。如果它運行時沒有錯誤消息,則表明文件是空的 - 是否已手動打開文件以確認是否有要打印的信息? – abought

回答

0

無需關閉並重新打開文件。

target.write("%s\n%s\n%s\n" % (line1, line2, line3)) 
target.close() #Need to close the file when done editing, or else cant open. 

print "Here's the updated file!" 
txt = open(filename) 
print txt.read() 

你只需要打開「W +」模式下的文件,然後你可以seek()定位0;文件的開始。

target.write("%s\n%s\n%s\n" % (line1, line2, line3)) 
target.seek(0) 

print "Here's the updated file!"  
print txt.read() 

當您打開該文件與「W」或「W +」,它會刪除該文件中寫入內容 - 沒有理由truncate()它。