Home > Back-end >  write and save a txt file using spyder
write and save a txt file using spyder

Time:02-10

I am trying to write a txt file from Python:

for i in range(len(X)):
    k =1
    g.write('CoordinatesX=' str(i) str(X[i]) '\n')
    g.write('D' str(k) '@Sketch' str(sketch_number) '=CoordinatesX' str(k) '\n')
    k =1
    g.write('CoordinatesY=' str(i) str(Y[i]) '\n')
    g.write('D' str(k) '@Sketch' str(sketch_number) '=CoordinatesY' str(k) '\n')
    k =1
    g.write('CoordinatesZ=' str(i) str(Z[i]) '\n')
    g.write('D' str(k) '@Sketch' str(sketch_number) '=CoordinatesZ' str(k) '\n')
        
g.close()

I get no error, but then when I go to look for the downloaded file, I don't find it, and nothing was written. Does someone know what I am doing wrong? Thank you so much already. cheers!

CodePudding user response:

In Python you can open a file this way:

file = open('file.txt', 'r ')
file.read() # This will return the content
file.write("This file has just been overwritten")
file.close() # This will close the file

A better practice is to use the with/as syntax:

with open('file.txt', 'r ') as file:
    file.read()
    file.write("This file has just been overwritten")
# The file is automatically closed (saved) after the with block has ended
  • Related