我需要一些幫助,我試着用這個代碼打印.txt文件的Python
text = open('C:\\Users\\Imran\\Desktop\\text.txt',"a")
rgb = text.write("foobar\n")
print (rgb)
text.close()
由於某種原因,持續顯示一個數字來顯示文本文件的內容(FOOBAR)。如果有人可以提供幫助,那就太棒了,先謝謝了
編輯:我正在使用Python 3.3。
我需要一些幫助,我試着用這個代碼打印.txt文件的Python
text = open('C:\\Users\\Imran\\Desktop\\text.txt',"a")
rgb = text.write("foobar\n")
print (rgb)
text.close()
由於某種原因,持續顯示一個數字來顯示文本文件的內容(FOOBAR)。如果有人可以提供幫助,那就太棒了,先謝謝了
編輯:我正在使用Python 3.3。
打印此文件的內容:
with open(filename) as f:
for line in f:
print(line)
使用with
來確保文件句柄在完成時將被關閉。
追加像這樣的文件:
with open(filename, 'a') as f:
f.write('some text')
感謝幫助我堆積如山的老兄,過去2小時我一直在這個問題上談論 –
如果你想顯示文件的內容以讀模式打開它
,然後使用
for line in f:
print(line) # In Python3.
打印文件的內容是的,不要忘記關閉文件指針f.close()
完成讀取後
您打印寫入的字節數。這是行不通的。您也可能需要將文件作爲RW打開。
代碼:
text = open('...', "a")
text.write("foo\n")
text = open('...', "r")
print text.read()
# Open a file
fo = open("foo.txt", "r+")
str = fo.read();
print "Read String is : ", str
# Close opend file
fo.close()
您打開一個文本文件進行寫入,並期望從中讀取的東西嗎? – Matthias
我有點好奇,它一直在顯示一個數字,根據[documentation](http://docs.python.org/2/tutorial/inputoutput.html)''write''會返回''None'' 。 –