chapter five

5 Files

 

Files are an indispensable part of the world of computers, and thus of programming. We read data from files, and write to files. Even when something isn’t really a file — such as a network connection — we try to use a similar interface to files, because they’re so familiar.

To normal, everyday users, there are different types of files — Word, Excel, PowerPoint, and PDF, among others. To programmers, things are both simpler and more complicated. They’re simpler, in that we see files as data structures to which we can write strings, and from which we can read strings. But files are also more complicated, in that when we read the string into memory, we might need to parse it into a data structure.

Working with files is one of the easiest and most straightforward things you can do in Python. It’s also one of the most common things that we need to do, since programs that don’t interact with the filesystem are rather boring.

In this chapter, we’ll practice working with files — reading from them, writing to them, and manipulating the data that they contain. Along the way, you’ll get used to some of the paradigms that are commonly used when working with Python files, such as iterating over a file’s contents and writing to files in a with block.

5.1  Last line

5.1.1  Solution

5.1.2  Discussion

5.1.3  Beyond the exercise

5.2  /etc/passwd to dict

5.2.1  Solution

5.2.2  Discussion

5.2.3  Beyond the exercise

5.3  Word count

5.3.1  Solution

5.3.2  Discussion

5.3.3  Beyond the exercise

5.4  Longest word per file

5.4.1  Solution

5.4.2  Discussion

5.4.3  Beyond the exercise

5.5  Reading and writing CSV

5.5.1  Solution

5.5.2  Discussion

5.5.3  Beyond the exercise

5.6  JSON

5.6.1  Solution

5.6.2  Discussion