In this video, we're going to look at how to read Text Files in Python
Hi, my name is Art, and I teach Python at Noble Desktop. In this video, I'm going to show you how you can read data from a text file.
We don't have a text file that we can read data from, so let's create one. I'm going to copy some text from CNN.com and write the data into a text file. Now, that's my text file.
I'm going to read data from that file. This data comes as a plain vanilla string. Let's assign it to a variable name, "data", and use type on "data". That's a string.
Now, I want to get rid of all the "Monday, give me a call next Monday" stuff. To do that, I'm going to use the "split" method. It's a little bit confusing because "split" comes from a string, but always returns a list.
I'm going to split it by all the exclamation points and assign it to a variable name, "list". I'm going to run "len" on that list and now I have one huge string within that list. I'm going to assign it to a variable name "string".
Now, suppose I want to go word by word. I'm going to split "string" again and leave it blank. Now, I have a bunch of words. I'm going to call it "words".
Maybe I want to count how many times they use the word "there". I could convert it to lowercase and create a counter. I'm going to set it to 0 and loop through "words". If I find the word "there", I'm going to update the counter.
Counter would be 9, so apparently they use "there" 9 times in that text.
The main idea behind this exercise is that you can use "open" to read data from a text file and then you can do whatever you like with the string. You can split it, apply lower or upper, etc. That's a string. All right, thank you.