Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
Python has some very simple built- in functions for dealing with files. Let's make a working copy of files.py. I'll call it files-working.py and we will open that working file and we see here a simple loop that reads lines from a file and prints them out. So run that and see what it does. It prints out the lines of this file. This is the file here, lines.txt, and we are just printing out all five lines with that file in this little loop. What we are going to look at in this movie is this open function.
It's very simple and it has a few options. By default, all it does is it opens the files in the read mode and you give it a file name here and it returns the file handle object, which can then be used to operate on the file. If you don't specify it, read mode is the default and that looks like this. There is the second argument, which is the mode, and that defaults to the r character for read. Options there are r for read, w for write, or a for append.
Append is a special write mode. It sets the current position of the file to the end of the file so that everything that you write will get appended to the file. In read mode, you can optionally give it a plus sign, which will open it for both read and write in the same file handle object. You can also give it a t for text file mode or a b for binary mode, and we will look at these options a little later in our movie on the subject. The open function returns this file handle object, which we see used here.
It is an iterable object and in iteration mode it simply gives you one line of the file at a time. In fact, there is a method called read lines, which does exactly the same thing. You save that and run it, and there is our lines of text. So that is the open function in all of its simplicity. In the rest of this chapter we will look at how to read and write files and how to set its file mode.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 97517 Viewers
61 Video lessons · 84757 Viewers
71 Video lessons · 68937 Viewers
56 Video lessons · 101383 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.
Your file was successfully uploaded.