Saturday, January 23, 2021

How to write to a file

Let's start by generating some data. 

x1 = [1,2,3,4,5]

y = x1**2

We want to write the data into file named test1.txt. To write into this txt file first we need to create the txt file. This is done by writing the following command 

file = write("test1.txt", "w")

Now to write x value and the corresponding y value at each line we need to create one for loop. 

for i in range(len(y)):

    file.write(str(x[i]) + "\t" + \

                    str(y[i]) + "\n")

After exiting the for loop the file must be closed. This is done by writing the following command. 

file.close()

 

No comments:

Post a Comment