English subtitles

← Reading from a File - Programming Foundations with Python

Get Embed Code
7 Languages

Showing Revision 4 created 05/25/2016 by Udacity Robot.

  1. So, here is our plan for the project. I will
  2. start with step one, which is reading text. Now, here is
  3. the file I want to check for curse words. For
  4. now, I have some famous movie quotes in here. By the
  5. way, this file could have contained some other text, like
  6. the draft of an email or an article you wrote. I
  7. have named this file movie_quotes.txt. Now, if you want to use
  8. this exact file in this program. It is available for you
  9. to download in the instructor notes. But you should
  10. feel free to use any other text file on your
  11. computer as well. Okay, let's start writing code. Now,
  12. I created a program called check_profanity.py. You could have called
  13. it something else as well. Inside it, I created
  14. a function called read_text, which is empty for now. Now,
  15. I know there is this function in Python called open,
  16. which allows you to work with files on your computer.
  17. This function takes in the address or the location of the file you want to open.
  18. So, on a Windows machine, I will browse
  19. to my file, which is movie_quotes.txt. Copy its location.
  20. Paste that. And then add the file name
  21. I want to open, which is movie_quotes.txt. Now,
  22. if you're on a Mac, there is a helpful document in the instructor notes for you.
  23. That document will tell you how to get the location of this file on a Mac.
  24. I will refer to this file as quotes.
  25. Now that I have a way of accessing movie_quotes.txt,
  26. I will use a function called read. So,
  27. I will say, quotes.read. This will allow me
  28. to read the contents of movie_quotes. So, let
  29. me save that in a variable called contents_of_file. Let
  30. me print out those contents. And it's also
  31. a good convention to close out any file that
  32. we've opened through the program. Okay. Now, I'm
  33. going to save and run this program and see
  34. where it gets us.
  35. And boom. Here is that output window with all
  36. of the movie quotes that we had read from the
  37. text file. Now, I don't know about you. But
  38. it just blows my mind that we can read from
  39. a text file with only a few lines of
  40. code. Okay, so I am back at our program. Now,
  41. before I continue to execute any more of plan. Let's
  42. find out a bit more about this function called open.