File operations in Python

A file is an object that stores data. Python can be used to read files and also to write to files. In today’s blog , I will show you how to write into a file and also how to read data from a file. 

First let us learn how to write to a file from a python code.



In the above python program , we first define the string called “text”. The open(filename,mode) function is used to open files. The filename is the name of the file to be opened. Mode refers to the way the file is going to be opened . It will be “r” for reading,”w” for writing and “a” for appending.

Here it is ‘w’ for writing.

The .write function writes the string into the file. The .close function closes the file after performing the operation on it. 

The file with the name “myfile” is saved wherever the above code is present.

Screenshot (80)

 Now let us see how to read from a text file using Python code.


We use ‘r’ for reading from the file.












Image Courtesy: Google Images






Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by

Up ↑

%d bloggers like this: