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.
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