質問

I was just trying to add a string to end of file, but I can't get it to work. I get this error:

IOError: (9, 'Bad file descriptor')

I get it on line 123. It's in the code below, but marked with #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

Thanks in advance, Amar!

P.S. If you need any more information, please ask for it in comments!

役に立ちましたか?

解決 2

You need to open the file for reading in order to use .read()

You have only opened it for writing with "wb".

Use "rb" to read, "wb" to write, and "ab" to append

adding a '+' like "ab+" allows for simulaneous reading and appending/writing

There is a reference for the different modes here

Example:

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

他のヒント

You want 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.

Also with "append" mode you don't even have to read the existing content, seek(0) etc, you can just plain write:

bruno@betty ~/Work/playground $ cat yadda.txt
foo
bar
bruno@betty ~/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()
>>> 
bruno@betty ~/Work/playground $ cat yadda.txt
foo
bar
newline here
bruno@betty ~/Work/playground $
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top