我從eclipse運行這個,我正在使用的文件名是ex16_text.txt(是的,我輸入的是正確的。它正確寫入文件(輸入出現),但是「print txt.read )」似乎並沒有做任何事情(打印一個空行),請參閱該代碼後的輸出:Python基礎知識 - 爲什麼我的文件內容不打印?
filename = raw_input("What's the file name we'll be working with?")
print "we're going to erase %s" % filename
print "opening the file"
target = open(filename, 'w')
print "erasing the file"
target.truncate()
print "give me 3 lines to replace file contents:"
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "writing lines to file"
target.write(line1+"\n")
target.write(line2+"\n")
target.write(line3)
#file read
txt = open(filename)
print "here are the contents of the %s file:" % filename
print txt.read()
target.close()
輸出:
什麼是我們將要使用的文件名ex16_text.txt 我們要刪除ex16_text.txt 打開文件 刪除文件 給我3行代替文件內容: l國家統計局1:三 2號線:二 3號線:一個 書寫線在這裏提交 是ex16_text.txt文件的內容:
Thanks-我還沒有學會「與」呢,所以你的答案包含了更多的複雜性比我一直在尋找)。 – Olegious 2010-11-12 00:20:57
沒有太多的複雜性,現在你知道並可以開始使用它。試試:) – dutt 2010-11-12 00:26:17