2013-12-15 36 views
1

我只是想添加一個字符串到文件結尾,但我無法讓它工作。我得到這個錯誤:在Python中添加文件末尾的東西?

IOError: (9, 'Bad file descriptor') 

我得到它的行123這是在下面的代碼,但標有#hashcomment:

pluginlokacija2 = os.path.realpath("%s/plugins"%os.getcwd()) 
fo = open("%s/TwistedJobs/config.yml"%pluginlokacija2, "wb") 
old = fo.read() #this is line no. 123 
fo.seek(0) 
fo.write("%s\n- %s\n " % (old, event.getPlayer().getName())) 
fo.close 

在此先感謝,阿馬爾!

P.S.如果您需要更多信息,請在評論中提出要求!

+3

你打開文件進行寫入,但後來試圖從中讀取。 – martineau

回答

1

您需要打開文件,以便使用.read()

你只打開了它與"wb"寫讀書。

使用"rb"讀,"wb"寫,和"ab"追加

添加'+'"ab+"允許simulaneous讀取和附加/寫入

有不同模式的基準here

示例:

with open("filepath/file.ext", "ab+") as fo: 
    old = fo.read() # this auto closes the file after reading, which is a good practice 
    fo.write("something") # to the end of the file 
+0

這工作就像一個魅力,謝謝! –

3

你想open(filename, "ab+")

The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing.

與「追加」模式下,你甚至不必閱讀現有的內容,尋求

而且(0)等,你可以只是簡單的寫:

[email protected] ~/Work/playground $ cat yadda.txt 
foo 
bar 
[email protected] ~/Work/playground $ python 
Python 2.7.3 (default, Apr 10 2013, 06:20:15) 
[GCC 4.6.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> f = open("yadda.txt", "a+") 
>>> f.write("newline here\n") 
>>> f.close() 
>>> 
[email protected] ~/Work/playground $ cat yadda.txt 
foo 
bar 
newline here 
[email protected] ~/Work/playground $ 
+0

它的工作原理,但它不會追加到最後?http://pastebin.com/mnjbpy0w –

+0

你不必讀取/連接/尋找(0)與'追加'模式 - 只需寫你有什麼至。 –