我只是想在文件末尾添加一个字符串,但我无法让它工作。我收到这个错误:
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
提前致谢,Amar!
P.S。如果您需要更多信息,请在评论中提出要求!
答案 0 :(得分:3)
您想要open(filename, "ab+")
:
模式可以是'r','w'或'a'用于阅读(默认),写作或 追加。如果文件在打开时不存在,则将创建该文件 写作或追加;打开时会被截断 写作。在二进制文件的模式中添加“b”。添加'+'到 模式允许同时读写。
另外,使用“追加”模式,您甚至不必阅读现有内容,搜索(0)等,您可以简单地写一下:
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 $
答案 1 :(得分:1)
您需要打开文件进行阅读才能使用.read()
您只能使用"wb"
开启该作品。
使用"rb"
阅读,"wb"
撰写,"ab"
添加
添加'+'
类"ab+"
可以同时阅读和附加/写作
有不同模式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