How do I replace a line in Python
<p>I am trying to write a program in Python for an assessment where I have to update a stock file for a shop.</p>

<p><a href="http://i.stack.imgur.com/0OV0L.jpg" rel="nofollow">My instructions</a></p>

<p>My code so far:</p>

<pre class="lang-python prettyprint-override"><code>#open a file in read mode
file = open("data.txt","r")
#read each line of data to a vairble
FileData = file.readlines()
#close the file
file.close()

total = 0 #create the vairble total
AnotherItem = "y" # create
while AnotherItem == "y" or AnotherItem  == "Y" or  AnotherItem ==  "yes" or  AnotherItem ==  "Yes" or  AnotherItem ==  "YES":
        print("please enter the barcode")
        UsersItem=input()
        for line in  FileData:
                #split the line in to first and second section
                barcode = line.split(":")[0]
                item = line.split(":")[1]
                price = line.split(":")[2]
                stock = line.split(":")[3]

                if barcode==UsersItem:
                    file = open("data.txt","r")
                    #read each line of data to a vairble
                    FileData = file.readlines()
                    #close the file
                    file.close()
                    print(item +"       Â£" + str(float(price)/100) + "      Stock: " + str(stock))
                    print("how many do you want to buy")
                    HowMany= input()
                    total+=float(price) * float( HowMany)
                    file = open("data.txt","a")
                    StockLevel=float(stock)
                    file.write(item + ":" + price + ":" +str(float((StockLevel-float(HowMany)))))
                    file.close()
                    print("Do you want to buy another item? [Yes/No]")
                    AnotherItem = input()
        if AnotherItem == "n" or "N" or "no" or "No" or "NO":
                print("total price: Â£"+ str(total/100))
</code></pre>

<p>
When I try to update my stock file it writes to end of the data file, instead of over the line I want it to.</p>

<pre><code>file = open("data.txt", "a")
</code></pre>

<p>Opens the file in append mode, means writing to the end of the file without overwriting data (adding to it, not changing).</p>

<p>Use </p>

<pre><code>file = open("data.txt", "w")
</code></pre>

<p>Instead, to flush the file contents and overwrite them.</p>

<hr>

<p>If you have some lines, and you only want to change the last do as follows:</p>

<pre><code>data = open("data.txt").read().split("\n")
</code></pre>

<p>get an array of the file lines.</p>

<pre><code>data[-1] = new_line_contents
</code></pre>

<p>change the last line to the new content.</p>

<pre><code>open("data.txt", "w").write("\n".join(data))
</code></pre>

<p>write back with flushing the new data (join the elements in data with newline between them)</p>

python