在Python文件末尾添加什么?

2024-10-02 06:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是想在文件末尾添加一个字符串,但我无法使其正常工作。我得到这个错误:

IOError: (9, 'Bad file descriptor')

我在123号线找到的。它在下面的代码中,但用#hashcomment标记:

^{pr2}$

提前谢谢你,阿玛!在

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


Tags: 文件字符串代码标记信息错误评论file
2条回答

要使用.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

您想要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)等,您只需简单地写入:

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 $

相关问题 更多 >

    热门问题