--Originally published at Coding The Future
Original image by Romain Vignes.
Hello! Ok, I must begging by saying that reading this article will not kill you nor hurt you in any way. In fact, it will be beneficial! So why the title, you may ask? Just to catch your attention! ?
Today's topic is reading and writing text files. This is one of the most important aspects in programming, because if you think about it, 99% of things online are text-based. Think about it... although Google has the option to search through voice and image, 99.9% of the times you probably just type what you need to find and hit enter. See? This is why programs must be able to interpret text because we live in a text-based world.
I want to get things clear though... When I say text files, I am not referring to MS Word documents –those are processed word docs– instead of plain .txt files. Let's get going.
Opening text files
Let's begging by looking at how to open a text file, which is the first step to reading or writing on the file.
In order to do this, we will need to declare a variable where a text file object will be stored. To do so, use the open( ) method and pass the filename as a parameter.
textFile = open(loremIpsum.txt)
Reading text files
Once we have the text stored in textFile, our sample variable, we can read it to process its contents. To do so, we need to use the .read() function.
In the following sample code, I read the text file I previously imported and print it:
print(textFile.read())
As you can see, since the text file is already stored in the textFile variable, I use the function within the file object.
Processing files
By processing, Continue reading "DO NOT READ THIS!!" →