You are on page 1of 8

FILE HANDLING IN PYTHON

WRITING DATA TO FILES


Create a new folder test in c drive of computer and then create a notepad file
a.txt in test folder as shown below. There is no need to save data initially. An
empty file would be ok in the beginning.

There is no need to save anydata initially. An empty file would be ok in the


beginning.

Because we want to write something in the file using python, we need to open the
file in write mode.
infile=open('c:/test/a.txt','w') this command would be used to open the file in write mode.
Infile is just a simple variable for file name you can have any other name for this variable.
w is used to specify mode. W has specified that we want to open file in write mode.
Filenamevariable.wirte(string) is used to write data into file

Open the file again to check the whether text has been written into file or not.

You can use \n at the end of the string to start new line file.
Dont forget to close the file when you have completed your task. Filevariable.close
commonad is used to close the file.

READING DATA FROM FILES


In order to read data from file, we need to open any file in read mode and r
is used to specify that we are opening file in read mode and as we created
the infile variable to handle to file in previous example we also need a
variable to open the file. I shall use our old variable.

filevariablename.readline() is used to read data from file. We need to store


the read data into separate variable.

As you can see from output that only one line has been read

To read the second line of the file, you need to again run readline(). Readline
start reading data from the beginning of the line and keep reading until line
finishes. As soon as the line finishes it stop reading the data. Then to capture
the data from the next line, we need to apply readline() again. As shown
below
Output windows showing the output of two variables

Reading data from files without applying .readline() again and again.
FILE PROCESSING EXAMPLE
Suppose we want to copy the content of one file to another file. One file has
32.0,54.0,67.5,80.25,115.0, we want to copy these float values to other file.

We shall use two files for the above example. file1 contain input data values, file2
shall be used as file that contain the final output.

You might also like