954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Automatically writing a new line in a txt file?

I'm pretty new to programming, so this may be really obvious, but I'm having trouble with it. I'm trying to learn python, so I thought I'd make a simple program in python to help me write similar lines of java code faster, (I'm going to easily have hundreds of lines of this.) and I've got it all worked out, except one little thing, which I'm sure is very simple, but I searched around a bit for it, and couldn't find anything, so I thought I'd just ask here before going to bed.

As you can probably tell, this will take the variables I set in the program, and then write out one line of code to the text file... but it always only writes to the first line, and overwrites everything in the file, even what is on other lines. I need it to automatically go to the next empty line, and write there instead. Could you guys give me a hand?

(Time for bed. Zzz.... lol)

def applybutton(self, event):
        X = XCOORD.GetValue()
        Y = XCOORD.GetValue()
        Z = YCOORD.GetValue()
        B = BLOCK.GetValue()
            
        file = open('Blueprints.txt','w')
        file.write('world.setBlockWithNotify(i ')
        file.write(`X`)
        file.write(', j ')
        file.write(`Y`)
        file.write(', k ')
        file.write(`Z`)
        file.write(', Block.')
        file.write(B)
        file.write('.blockID);')        
        file.close()
Lemony Lime
Newbie Poster
23 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

Use like this

file = open('Blueprints.txt','a')
file.write('world.setBlockWithNotify(i ')
file.write('X')
file.write(', j ')
file.write('Y')
file.write(', k ')
file.write('Z')
file.write(', Block.')
file.write('B')
file.write('.blockID);')   
file.write('\n')     
file.close()
bawakrbs
Newbie Poster
4 posts since Nov 2011
Reputation Points: 10
Solved Threads: 2
 

Or even

with open('Blueprints.txt','a') as file:
    file.write(
        "world.setBlockWithNotify(i {X}, j {Y}, k {Z}, Block.{B}.BlockID);"
        .format(X=X, Y=Y, Z=Z, B=B))
Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

Ah, thank you. None of the tutorials I read ever mentioned that you could use 'a' to append while writing to files, so I never even considered it.

Lemony Lime
Newbie Poster
23 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: