Writing data to file in Python

Writing data to file in Python

Writing data to the file is another important topic need to be discussed for Data file handling in Python. We can write data to file by using write() or writelines() function. write() function takes string as argument where writelines() takes list of lines as argument. But before all these thing we need to open the file object by using open() function with w or a as file mode. For example –

fout = open(‘address.txt’, ‘w’) here file mode used is w in place of that we can use a as file mode. The difference between w and a is when you will open a file with write mode it will create a new file called address.txt or else if file exist will delete all existing data from the file and start writing from the first line. Where as when you open a file using append mode will create a new file if not exist else will start writing to the file at the last position in a file. Now lets see the example of writing data into file –

Code to write date to file

The output of the program will look like this –

The first output section is taking input from user till your says n. And next output is displaying all the content appended at the list of the file.

If want to discuss something, feel free to comment. Thank you.

File Handling – Reading data from text file

Reading data from text file

Python supports file handling and allow to read and write data from file . Python supports two kind of files 1. text file 2. binary file. Text file is used to read and write data into file where data will store in human readable format and binary file will store the data in binary format which is readable using program only.

Now without wasting our time lets jump into example. So here is the example –

Code to read text file using read()

In this example we opened addr.txt file in read mode. The default mode is read mode only so you can write open(‘addr.txt’) is also valid. Now once the connection is established between file and file object you can call read() function on the file object. Next step is to print. Last but very important work is to close the connection using close() function. Here is the output-

Output of read from file

That’s it. In next chapter we will discuss about reading data using readline() and readlines().