We all have came across handling files in some way. Be it a '.txt' file or a '.dat' or even a '.py' file that we use to write our Python Programmes.
So, files are something, where we store some information.
Say for example, we want to write the below paragraph to a file.
So, we want to store the four lines in a File and name the File as 'myfirstfile.txt'.
And in general, you need to follow the below steps create the file and write the lines :
Again, if you want to make some changes to the file(Say adding or deleting a few lines) :
Similarly, if you want to delete the 'myfirstfile.txt' :
Now, let us corelate, how can we achieve the same in Python.
The first thing is to open a file. And to open a file in Python, there is a Function called 'open( )' that accepts two Arguments. They are the name of the file (i.e. 'myfirstfile.txt') and 'Mode'.
A 'Mode' states, what you want to do with the file, once you open it. i.e. You can open a file to read it, to write something to it, to append it and create the file the first time you try opening it.
Below are the file Modes :
Along with the above four Modes, we can add two more modes :
Let us look at the below example to create a File named 'myfirstfile.txt'.
myfile = open("myfirstfile.txt", "xt")
Now, if you search the above file 'myfirstfile.txt' in the current directory. You can find an empty file 'myfirstfile.txt' in the current folder.
So, in the above example, we have created a blank file called named 'myfirstfile.txt' using the 'open( )' function.
The Function, 'open( )' has two Arguments. First argument is the File name (i.e. 'myfirstfile.txt').And the second Argument is the Mode(i.e. 'xt'). Where 'x' is the Create Mode and 't' is used to create a text file.
Next, let us see, how can we write the above lines to the file myfirstfile.txt.