2010-11-11 28 views
3

我從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文件的內容:

回答

4
target.write(line2+"\n") 
target.write(line3) 
target.close() #<------- You need to close the file when you're done writing. 
#file read 
txt = open(filename) 
6

你應該flush文件已寫入它之後確保字節已被寫入。另請閱讀警告:

注意:flush()不一定會將文件的數據寫入磁盤。使用flush()後跟os.fsync()來確保這種行爲。

如果您已完成寫入並希望以只讀訪問方式再次打開文件,則還應關閉該文件。請注意,關閉文件也會刷新 - 如果關閉它,則不需要先沖洗。

在Python 2.6或更新版本,您可以使用with語句自動關閉文件:

with open(filename, 'w') as target: 
    target.write('foo') 
    # etc... 

# The file is closed when the control flow leaves the "with" block 

with open(filename, 'r') as txt: 
    print txt.read() 
+0

Thanks-我還沒有學會「與」呢,所以你的答案包含了更多的複雜性比我一直在尋找)。 – Olegious 2010-11-12 00:20:57

+1

沒有太多的複雜性,現在你知道並可以開始使用它。試試:) – dutt 2010-11-12 00:26:17