OVERVIEW
In this blog post, you will learn,
- What is file handling in python?
- Creating files in python
- Read/Write operations in files
File Handling in Python
Files are the named locations on the drive to store the related information. They are used to store the data permanently in a non-volatile memory like hard disk. As we know that Random Access Memory(RAM) is volatile memory as it losses the data on power off. So, we use files for future use to store the data permanently.
Whenever we want to do some operations (like reading or writing) on a file, we need to open it first and when we are done we need to close it so that the resources that are tied with the files are freed.
File operations take place in following order:
- Open a file
- Read or write operations
- Close the file
Creating Files in python
In python, to create a file we need to first follow the above order as opening a file for file handling is the first step in every mode. To open a file in python we use the inbuilt function open(). This function requires at least one argument, i.e., file name and second argument is mode having a default value to read the file that can be changed based on the operation to perform and rest of the arguments are not mandatory so we can leave them as it is. Now let’s understand file handling by creating the first file with python.
file = open('demo.txt', 'w')
With the above code we are opening a text file(i.e., demo.txt ) in write mode and creating an object. With this command it will create a new file on the current directory with the name provided and if the file with the same name already exist in that case it will use the existing file and will overwrite the data into it.
file.write("Hello Folks!!!\n")
file.writelines(['Welcome ', "to ", "Innovate Yourself"])
From the above line the string data will be added to the file that we are creating. With file.write() we can send only one string at a time and add it to the file. With file.writelines() we can send multiple strings in a list or tuple format at once. Once you are done with adding all the data to the file, close it with the below command.
file.close() print("Data added successfully.")
Here is the full code:
file = open('demo.txt', 'w')
file.write("Hello Folks!!!\n")
file.writelines(('Welcome ', "to ", "Innovate Yourself"))
file.close()
print("Data added successfully.")
On executing the code above you will get the below results.
For more details and clarification check our video,
Read Operation For File Handling
Like in the above code you have seen that how you can create a file with python to store the data. Now let’s understand that how we can read the file that we have just created(i.e., demo.txt). Now let’s start with the first step like we have done above, i.e., to open the file. The only change here will be to open the file in read mode.
file = open('demo.txt', 'r')
with the above command we have opened the file in read mode, which means that now we can read all the data that we have in demo.txt file. Now, we will read the data from the given file in different ways.
print(file.read())
This command will read all the data from demo.txt file and it will print it on the output window. But if I want to pick all the data from different lines as a single element then how can we do its? That is shown here,
print(file.readlines())
This will read all the data from the file and will return a list that will contain each line as a single element of a list. Here, we have one issue and that is, if I will use the command file.read() twice or thrice then I will get the data printed only once as per the first command and nothing in other cases. So how to handle that in file handling?
To do that we need to reposition the cursor for file object to start reading the data from the beginning, because after every read function the cursor moves to the end and tries to read the data from the end position as a result it doesn’t get anything to print.
Full code to handle it:
file = open('demo.txt', 'r') print("First read: ",file.read()) print("Second read: ",file.read()) print("Position:",file.tell()) file.seek(0,0) print("Position:",file.tell()) print(file.read()) print("Position:",file.tell()) file.seek(0,0) print(file.readlines()) file.close() print("Data read successfully.")
On executing the above code you will understand what happens if you try to add file.read() twice. Here is the output.
For more clarification check this video,
Above, I have shown you two ways to for file handling. In the similar way you can open the file in different other modes and perform the various operation for file handling. Few modes for file handling are shown below.
Mode | Description |
r | Opens a file for reading. (default) |
w | Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists. |
x | Opens a file for exclusive creation. If the file already exists, the operation fails. |
a | Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist. |
t | Opens in text mode. (default) |
b | Opens in binary mode. |
+ | Opens a file for updating (reading and writing) |
These are the different modes for file handling which you can use while opening the file.
Time to wrap up now. Hope you liked our content on FILE HANDLING IN PYTHON. See you in our next blog, thanks for reading our blog and do leave a comment below to help us improve the content to serve you all of our experience with you. Stay tuned with us for more python contents.
Also check out our other playlist Rasa Chatbot, Internet of things, Docker, Python Programming, etc.
Become a member of our social family on youtube here.
Stay tuned and Happy Learning.