user1294039
user1294039

Reputation:

Can only write newlines to file

I have the following script:

import random

def mf():
    filename = raw_input("file: ")
    string="a"
    while (string):
        string = raw_input("ID\n")
        string += " | "
        string += raw_input("Title\n")
        string += " | "
        string += raw_input("Artist\n")
        string += " | "
        string += raw_input("Kind\n")
        string += " | "
        string += raw_input("Year\n")
        string += " | "
        string += raw_input("Ranking\n")
        string += " | "
        string += raw_input("Purchased\n")
        string += " | "
        string += raw_input("c\n")
        f = open(filename,'w')
        print string
        f.write(string)
        f.write("garbage")
        f.write("\n")
        f.close()
        string = raw_input("...")
    n = random.randint(1,4)
    f = open(filename,'w')
    for i in range(n):
        f.write("\n")
    f.close()

It writes the newlines fine, when I print the string I get what I expect, but neither "garbage" nor string is ever written.

Upvotes: 2

Views: 77

Answers (1)

wheybags
wheybags

Reputation: 657

That's because you open it again as write just after. If you want to append to a file, use:

f = open(filename, "a")

When you open it with "w", you overwrite the current contents of the file. But it would probably be better to just open it once and close it once.

Upvotes: 4

Related Questions