這個程序只需要一個文件,刪除它,允許用戶輸入兩行放入空白文件,然後打印文件。必須先閱讀文件才能關閉文件? Python
但是爲什麼我必須關閉文件對象並在顯示新添加的行之前重新打開它?
(注意該文件沒有在這個版本的代碼打印,但如果去掉#的就正確執行。)
from sys import argv
sript, filename = argv
print "We will be buliding a new file from an %s" % filename
print "If you don't want to do this, hit CTRL_C"
print "If you do, hit and other key"
raw_input(">>>")
print "Oppening the file..."
file_ob = open(filename, "r+")
file_ob.truncate()
print "Now we will rewrite this file with the following line"
line1 = raw_input("The fist line will be :")
line2 = raw_input("The second line will be:")
print "Now we're put them into the file"
file_ob.write("\n\t>>>" + line1 + "\n\n\t>>>" + line2)
print "And now we will see what is in the file we just made"
print file_ob.read()
file_ob.close()
print "And now we will see what is in the file we just made"
#file_ob = open(filename, "r+")
#print file_ob.read()
#file_ob.close()
該文件被緩衝。關閉它時,它會強制緩衝區被刷新並寫入文件。考慮使用'open(filename,「r +」)作爲file_ob:'以避免需要關閉。 –
您也可以使用'os.SEEK_SET',因此寫入後不需要關閉和重新打開以讀取文件。 –
@ l'L'l:'os.SEEK_SET'只是一個常量(不是必需的;'SEEK_SET'是默認模式)。你的意思是'file_ob.seek(0)'(第二個參數默認爲'SEEK_SET')? – ShadowRanger