1,105,229 Community Members

Automatically writing a new line in a txt file?

Member Avatar
Lemony Lime
Light Poster
25 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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()
Member Avatar
bawakrbs
Newbie Poster
4 posts since Nov 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
1
 

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()
Member Avatar
Gribouillis
Posting Maven
3,452 posts since Jul 2008
Reputation Points: 1,140 [?]
Q&As Helped to Solve: 883 [?]
Skill Endorsements: 18 [?]
Moderator
 
1
 

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))
Member Avatar
Lemony Lime
Light Poster
25 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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.

Question Answered as of 2 Years Ago by Gribouillis and bawakrbs
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: