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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>