Learner
Learner

Reputation: 483

How to add new lines to a file without appending again and again?

I have a script which is adding the output to a file as follows:

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)

the change_log.txt looks as follows:

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

Now the new file where i am adding the output "my_log.txt" only contains :

\item welcome

but i want it to have all the three lines as follows:

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

I tried using:

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

but here i face one problem when the script is executed once i do get the output as the three lines but if script is executed number of times output i get is as :

    \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

So that i dont want. i just want to get ouput added in the same file without appending again and again. so, how shall i achieve that.

Upvotes: 2

Views: 98

Answers (3)

Vlad M
Vlad M

Reputation: 477

You have a typo with fobj (in second alias).

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

When opening a file for reading, 'r' reading mode is assumed unless overridden. https://docs.python.org/2/library/functions.html#open

Also, you don't need to use .writelines but .write as all you write is a single string. https://docs.python.org/2/library/stdtypes.html?highlight=writelines#file-objects

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174624

Everytime you open the file with w, the file is truncated (that is, anything in it is deleted and the pointer is set to 0).

Since you are opening the file in your loop - it is actually writing all the strings, but since its opened in each loop iteration, the previous string is deleted - in effect, you are only seeing the last thing it writes (because after that, the loop finishes).

To stop this from happening, open your file only once for writing, at the top of your loop:

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)

Upvotes: 3

MTroy
MTroy

Reputation: 895

it should be

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

Upvotes: -1

Related Questions