Ian Zane
Ian Zane

Reputation: 2389

Writelines (python) clears the text file it is supposed to write to, and writes nothing

What I'm doing is pretty basic, but for some reason isn't actually writing anything into the text file I need.

The first thing I've done is gotten input from the user and assigned it to assoc. This works fine, as I can print out assoc whenever I please, and that appears to work completely fine.

Next, I open a different file depending on whether or not assoc is equal to 0, 1, or 2. I read all the lines and assign the list of read lines to the variable beta, then I grab the length of beta and assign it to prodlen, add one two prodlen and assign that new value to localid and close the object. The only reason I'm including this is because I fear I've missed something crucial and simple.

if assoc==0:
    fob=open('pathto/textfile1.txt','r')
if assoc==1:
    fob=open('pathto/textfile2.txt','r')
if assoc==2:
    fob=open('pathto/textfile3.txt','r')

beta=fob.readlines();
prodlen=len(beta);
localid=prodlen+1;
fob.close;

After I get the user input, open the file, list its contents, and read its length, I then use the user's input again to open the file with writing permissions. (I've only included one of the possible if statements, because the others are identical except for which file they write to and what VALUE, which is a string, is). I append list beta with \n to get a line break, followed by a string, which has been represented here by VALUE. I then add localid onto the end, in string form.

if assoc==0:
    fob=open('pathto/textfile1.txt','w')
    beta.append("\nVALUE"+str(localid))
    print (beta)
    fob.writelines(beta)

My true problem, though, is in the last two lines. When I print out list beta, it includes the new value that I've appended. But when I try to write the list to the file, it clears any data that was currently in the file and doesn't write anything inside! I'm a python noob, so please, keep the solution simple (if possible). I assume the solution to this is relatively simple. I'm probably just overlooking something.

Upvotes: 2

Views: 4448

Answers (1)

Colleen
Colleen

Reputation: 25499

use the 'a' option instead of 'w' in your open call. w overwrites, a appends.

http://docs.python.org/2/library/functions.html#open

python open built-in function: difference between modes a, a+, w, w+, and r+?

is a useful explanation of different modes.

Upvotes: 2

Related Questions