Tuesday, January 26, 2021

How to read a file in python ?

 The command for reading the file is : 

file = open( "filename", "r")

"filename" is the name of the file, while "r" is the command for reading the file.  For example let's create .txt file with name readingtest.txt with the following dummy text. 

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

To open and read the file type in the python script following command. 

file = open("readingtest.txt", "r")

To read the file line by line type the following command: 

for line in file: 

    print("line = {}".format(line))

This output will be: 

line = Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

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()