如何在文件中添加新行而不需要一次又一次地追加?

2024-04-28 07:59:24 发布

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

我有一个脚本,它将输出添加到一个文件中,如下所示:

with open('change_log.txt', 'r') as fobj:
    for line in fobj:
        cleaned_whitespaces= line.strip()            
        if cleaned:
            var = "\item " + cleaned_whitespaces
        with open('my_log.txt', 'w+') as fobj:
            fobj.writelines(var)

变化_日志.txt如下所示:

- Correct reference to JKLR45, fixed file
- hello
- Welcome

现在我在新文件中添加输出“my_日志.txt“仅包含:

\item welcome

但我希望这三行都是这样的:

\item - Correct reference to JKLR45, fixed file
\item - hello
\item - Welcome

我试过使用:

 with open('my_log.txt', 'a') as fobj:
        fobj.writelines(var)

但在这里我面临一个问题,当脚本执行一次,我得到的输出是三行,但如果脚本执行的次数,我得到的输出是:

    \item - Correct reference to JKLR45, fixed file
    \item   - hello
    \item    -welcome
    \item - Correct reference to JKLR45, fixed file
    \item   - hello
    \item    -welcome
    \item - Correct reference to JKLR45, fixed file
    \item   - hello
    \item    -welcome

所以我不想要。我只想将输出添加到同一个文件中,而不需要一次又一次地追加。那么,我该如何做到这一点呢。你知道吗


Tags: 文件totxt脚本hellowithopenitem
3条回答

每次用w打开文件时,文件都会被截断(即删除其中的任何内容,并将指针设置为0)。你知道吗

由于您在循环中打开文件—实际上它正在写入所有字符串,但由于它在每次循环迭代中打开,上一个字符串将被删除—实际上,您只看到它最后写入的内容(因为在此之后,循环将完成)。你知道吗

要防止这种情况发生,请在循环顶部仅打开一次文件进行写入:

with open('change_log.txt', 'r') as fobj, \
     open('my_log.txt', 'w') as fobj2:
    for line in fobj:
        cleaned_whitespaces= line.strip()            
        if cleaned_whitespaces:
            var = "\item " + cleaned_whitespaces
            fobj2.writelines(var)

cleaned不存在,文件别名读写相同。
您正在打开文件以便在with语句中写入,最后应该有最后一个行。更改那个。你知道吗

试试这个:

fobjw = open('my_log.txt', 'w+')
with open('change_log.txt', 'r') as fobj:
    for line in fobj:
        fobjw.writelines("\item " + line.strip())
fobjw.close()  

有一个fobj(在第二个别名中)的拼写错误。你知道吗

with open('aaa.txt') as readable, open('bbb.txt', 'w+') as writeable:
...   for line in readable:
...     writeable.write("\item %s" % line.strip())

打开文件进行读取时,除非重写,否则将采用'r'读取模式。https://docs.python.org/2/library/functions.html#open

另外,您不需要使用.writelines而是.write,因为您所写的只是一个字符串。https://docs.python.org/2/library/stdtypes.html?highlight=writelines#file-objects

相关问题 更多 >