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 an interface similar 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.

Exercise 18 Final line

Working it out

Solution

Screencast solution

Beyond the exercise

Exercise 19 /etc/passwd to dict

Working it out

Solution

Screencast solution

Beyond the exercise

Exercise 20 Word count

Working it out

Solution

Screencast solution

Beyond the exercise

Exercise 21 Longest word per file

Working it out

Solution

Screencast solution

Beyond the exercise

Exercise 22 Reading and writing CSV

Working it out

Solution

Screencast solution