Python for Entrepreneurs Transcripts
Chapter: Appendix: Python language concepts
Lecture: Concept: File I/O
Login or
purchase this course
to watch this video and the rest of the course contents.
0:01
Working with files in Python, especially text files is something that you are likely to need in your application.
0:07
So let's take a really simple example. Here we are going to create a file,
0:12
we have three items in our data structure we want to save on the three separate lines, so we have cat, hat, mat and a list, and these are just strings.
0:19
We are going to use the "open" method, and the "open" method takes a file name and a modifier,
0:24
and then this "open" method, the open string that comes back can be used as a context manager, so we are putting into a "with" block,
0:31
and naming the variable fout for file output, and this automatically closes the file stream, as soon as we leave this with block.
0:39
So that's really nice and safe, makes sure we flush, it close it, all those kinds of things.
0:43
Once we get the file open, we are going to loop over each item and we are just going to say "fout.write" and pass it the item, so cat, hat or mat.
0:51
Now, write does not append a new line, it just writes characters to the file, so we want to say "\n" to append a new line,
0:58
so each one of these items up here is on a separate line in the file.
1:02
And notice this "w" modifier, this means write only and truncate the file if it exists. We could also say "a" for append, "a+" for create an append
1:12
or "r" if we just wanted to read from the file but not write to it. There is also a "b" modifier for binary files, but you'll use that less often.