Python 如何向文件中添加新行而无需一次又一次地追加?

Python 如何向文件中添加新行而无需一次又一次地追加?,python,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+') a

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

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)
- Correct reference to JKLR45, fixed file
- hello
- Welcome
\item - Correct reference to JKLR45, fixed file
\item - hello
\item - Welcome
更改_log.txt如下所示:

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)
- Correct reference to JKLR45, fixed file
- hello
- Welcome
\item - Correct reference to JKLR45, fixed file
\item - hello
\item - Welcome
现在,我添加输出“my_log.txt”的新文件只包含:

\item welcome
但我希望它包含以下三行内容:

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)
- Correct reference to JKLR45, fixed file
- hello
- 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
所以我不想要。我只想将输出添加到同一个文件中,而不需要一次又一次地追加。那么,我应该如何做到这一点呢

open('my_log.txt', 'W') to overwrite it

每次使用
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)

您输入了
fobj
(第二个别名)

打开文件进行读取时,除非被重写,否则将假定为读取模式


此外,您不需要使用
.writelines
,而是
.write
,因为您只需编写一个字符串

在以附加模式打开文件之前,您只需检查文件是否存在?请先在写入中为打开文件。在循环中追加并在第二天调用它?