gpt4 book ai didi

python - 在 Python 中的文件末尾添加一些东西?

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:00 28 4
gpt4 key购买 nike

我只是想在文件末尾添加一个字符串,但我无法让它工作。我收到此错误:

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

提前致谢,阿马尔!

附言如果您需要更多信息,请在评论中索取!

最佳答案

你想要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.

还有“附加”模式,你甚至不必阅读现有内容,seek(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 $

关于python - 在 Python 中的文件末尾添加一些东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20599079/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com