Learn Python With Dhawal - 16 - File Input and Output


I know I have been slow with the updates but I have been working on an idea to build a project for this little course book of mine. I had to sort through a lot of ideas on what to make the project on to keep it simple, fun and yet covering all the major aspects of a proper application development.

Then I realised I haven't posted about how to read write a file yet. So before we jump on the bigger projects, here are a few basics more here and there to finish. So let's begin.

File Handling

File handling is one of the most primitive and basic tasks that you should know to perform if you want to move ahead into application development using python. As the title suggests there's not much mumbo jumbo to learn on the coding spectrum but here, we have to cover up a lot on the theory part.

File permissions

Before we move ahead and start operating on a file. We need to know what are the file permissions and how to deal with them.

There are mainly 3 types of file permissions :

I am using the word 'mainly' because the words indicating the permission or some custom permissions might arise depending on what you've been working on. But here we would go with the vanilla ones.


  1. Read : This permission as it says, allows one to read the file.
  2. Write : This permission allows one to write the file.
  3. Read and Write or Append : The name of this permission can be seen different depending on the systems you are using but it simply allows one to access and write the content in the file.

File Operation Modes :

Here we have just like the permissions we have 3 modes in basic to perform various operations on the files.


  1. Read : When you open a file in this mode, you can read the contents of the file. This mode will give you error if the file you want to read doesn't exist.
  2. Write : When you open a file in this mode, you can write your desired content in the file. But be careful while opening a file in this mode as when you open the file in write mode, the previous content of the file gets deleted. The new content of the file will be whatever you entered after the opening the file. This will create a new file if the file you specified doesn't exist.
  3. Append : When you open the file in this mode, you can write your desired content in the file. The difference here is that if your file previously contained anything, it won't be deleted and the new content will be just written after where the previous content ends. If your file didn't have anything written inside then it will just write down new lines as you enter them. This will create a new file if the file you specified doesn't exist.
File Operations :

Open : As the name suggests, this is used to open the file to start working on it. If the name of the file you point at doesn't exist, it might throw an error or create one depending upon the mode you used to operate on the file.
Close : This is very important step, as most forget to close the file after operating on it. If you don't close the file after operating on it, it might cause errors in file or make the file entirely unusable or might just not save the content you had entered.
Create : This will be for creating a file.
Delete : This will be for deleting a file.


File Handling in Python

Now, above we discussed basics of file handling. Each language has its own way of handling files. Here we will discuss actual operations and modes in python to perform various file operations.

Mode Function
r Read the file, default value if you don't specify the mode.
w Write file, creates a new file if the mentioned file doesn't exist. Also, if existing file contains anything, that would be deleted.
a Write file, creates a new file if the mentioned file doesn't exist. Also, if the existing file contains anything, it would continue writing where the previous content ends.
x Create a new file and opens it, returns error if file already exists.
tOpens file in text mode, default value
b Opens file in binary mode. It's useful for images.

Open : This method uses two parameters, one is the location of the file in your storage and second is mode you want to open the file in.

Syntax :  open("fileaddress.extension", "Mode you want to open your file in")
example - f = open("demofile.txt","r"). This will open a file in read mode. Here, f is the file object created to operate on the file. Python follows OOPS concepts, hence we have to create object of file to use it.

Close : This method uses no parameters or arguments.

Syntax :  "fileObjectName".close()
example - f.close()

Input

import os
# First we will create a file.
f = open("C:/Users/joshidhawal/Documents/Git/learn-python-with-dhawal/testfile.txt","a+")
print("A new text file is created and opened in append+ mode")
# Writing in the file
f.write("Hello World! This is my first created file")
print("Message is written in file")
# Reading the written text
print("This is the position of cursor in the file : "+str(f.tell()))
f.seek(0)
print("We changed the cursor position to beginning,so now we can read the file.")
print(f.readline())
print("Message is read")
# Closing the file
f.close()   
print("File is closed")
# Delete the file
os.remove("C:/Users/joshidhawal/Documents/Git/learn-python-with-dhawal/testfile.txt")
print("File deleted")

Output

  1. A new text file is created and opened in append+ mode
  2. Message is written in file
  3. This is the position of cursor in the file : 42
  4. We changed the cursor position to beginning,so now we can read the file.
  5. Hello World! This is my first created file
  6. Message is read
  7. File is closed
  8. File deleted


Explanation :

First we create and open the file. Now if we just had to create the file we could've used the 'x' permission to create the file. We can add '+' to add more functionality. You can read more about the file operation modes by clicking here.

But here we used 'a+' as the file operation mode, meaning we are opening it as an append mode and allowing some more permissions to it. We are also printing the state of the file operations after each operation is performed. This is not needed but it can be used as a method of debugging or some sort of confirmation that the particular operation is been performed. Since Python is an interpreted language, all the print statements followed by the operation will indicated that the particular operation is been performed successfully.

Next we use the 'write' method to write into the file. After that we seek the current position of the cursor in the file. Now, remember that if you have to write again, it'll start writing after the previous position as you haven't closed the file yet. So if you wished to read whatever you've written, you'd have to get the cursor back on the the starting position.

Hence to do that we have used 'tell' method to show the current cursor position followed by using 'seek' method to move the cursor to the file beginning. Hence then we could read the message that we had written in the file. We read the content using the 'readline()' method since it's only one line. If we wanted to read the whole file and there was content of multiple lines or say maybe a paragraph we would be using 'read' method instead.

We close the file after performing the operations using 'close' method. Now the next step we take is totally optional and for educational info. At times you don't want to keep a particular file or delete it. If you run this program it won't give you any error as it is using append mode. But say, if you wanted to use create mode and then just leave file as it is and there was some file with the same name which you had created previously, you'd have to delete it.

So to delete the file we have created, we import the 'os' package and then use it to remove the file we had created.

~*~*~*~

This program gave you idea about how to perform most basic file operations using python. To know more you can refer the linked python official documentations or just try out yourself by experimenting and googling. It always helps to search and find out new tricks.

Try out yourself :

Write a program to create a file if not in existence. If it exists, open it and start writing information where the previous content had finished. At the end it should give read the whole file again. It should ask if you want to keep the changes or not. If yes, the previous message should be saved and file should be closed or else the file should be reverted to it's previous state.

<< PREVIOUS CHAPTER || NEXT CHAPTER >> --INDEX--


~*~*~*~

This series is totally authored by me (Dhawal Joshi). Any similarities found on the text, or codes or anything is purely accidental. All the sources of reference will be mentioned, linked and will be given the proper credits. If I miss anything or there's anything wrong, feel free to comment or send me an email and I'll try to edit it out. I am not a Python expert, I am sharing whatever I have learnt on my own and with a few sources around to refer from which will be mentioned. Also feel free to share this series with others so most can benefit out of it.

~*~*~*~




Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Are you getting regular fresh content updates? If not click on the button below.

0 comments:

Post a Comment

Do comment and share your thoughts.