Text Files in Python || Python Tutorial || Learn Python Programming

Files are everywhere in the digital universe. When you write a Python program, you save your code in a file. Starting an app with your VR eye implants will launch a cloud service that is also contained in a file. Even your operating system consists of a mountain of files. Working with files is an essential part of life as a software engineer.

So today we will learn how to read and write text files. And by the way. don’t be alarmed but the video you are now watching is stored in a file. There are two kinds of files: text and binary. Text files are generally human readable data, like plain text, XML, JSON, or even source code. Binary files are used for storing compiled code, app data, and media files, like images, audio, and video files.

Today we will learn how to read and write text files. To open a file in Python, you use the built-in open function. Let us take a quick look at the help text. This is a powerful and versatile function. There are pages of documentation on all the ways you can use this function. Today, we will focus on the file and the mode. For this video, we have created a folder to hold all the text files we will use.

As you can see the folder is currently empty. That is all about to change. Begin by making a sample text file, using your favorite editor. What a better example than a brief biography of Guido van Rossum, the creator of Python. This text file will be named guido_bio.txt To save time, I am pasting the text from the Benevolent Dictator’s personal website. Now, save and exit. As you can see, the file is there. Now let’s start Python and read it. One way to open a file is to call the open function with the name or path to the file. By default, it will open the file in read mode and return a file object which we call f. To read the contents of the file, call the read method. This will return all the text in the file. Finally, close the file.

We can now print the text to see that everything worked. It did. This method of opening, reading, and closing a file is simple. It only took three lines. But there is a danger. What if something goes wrong before you close the file? You do not want to litter your computer’s memory with open files. Because of this, there is a better and safer way to read files that is also 33% shorter. This method is to open a file using the with keyword. As before, the open function will create a file object and assign it to the name you specify. You can then read the contents like before, but with this technique you do not need to close the file. That is done for you. In fact, Python will close the file even if an exception occurs in the code block. That is first-class service, indeed. And just to be sure, print the text to check that everything worked. Bravo, Python. Bravo. But what happens if you try to open a file that does not exist? Then Python will raise a file not found error.

One way to handle this is to wrap the file code in a try block. We can then handle a file not found exception. For example, if the file does not exist, you might want text to store the value none. If you run this it displays none, since the file was not found. And if you replace the file name with the one we created earlier, it successfully reads the existing file.

Let us now see how to write to files. For an examplem we will write the names of the five oceans to a txt file. In this case, you need an additional argument to the open function: w for write. If you do not specify a mode, Python will open the file in read mode by default. Here, if the file oceans.txt does not exist, Python will create it. And if the file already exists, Python will overwrite it. So be careful. To write the names of each ocean to the file, loop over the list and use the write method.

Remember, when using the with technique for opening files, Python will automatically close the file for you. Let’s open the file and see if this worked. While it did write the ocean names, there are no line separators. That is because we did not write one, and Python does not assume we want them. One way to fix this is to write a new line after writing the name of each ocean.

Now, if you run the code, and then open the file, you will see each name is on a separate line. There is another way to ensure that each string is on a separate line. You can use the print function and have it print to the file by using the file keyword argument. If you run this, and look at the file, you get the same result.

Each name is on a separate line. Notice that every time we ran our code, any text in the file was overridden. This is because we open the file in write mode. But what if you would like to write to a file without overwriting any existing text? For this, you open the file in append mode by using an a after the file name. Append mode will create the file if it does not exist, but if the file does exist, then Python will append your text to the end. It will not overwrite any existing text. Let us see that this is the case. Run… and check… and applaud. With Python, reading and writing text files is a snap. And with Socratica, learning math and science is a breeze. To avoid missing any of our videos, open your browser…visit YouTube in append mode… and SUBSCRIBE to our channel. And you do not have to worry about closing your browser. Just keep watching our videos. There should be no exceptions… Thank you for watching Socratica..

As found on Youtube