Skip to Content
The Python Book
book

The Python Book

by Rob Mastrodomenico
January 2022
Beginner to intermediate
272 pages
6h 51m
English
Wiley
Content preview from The Python Book

14Dealing with Files

Thus far we have gone through what you can do with Python and the examples given have revolved around simple examples. In reality we want to work on data of some kind and as such we need to get it into Python. Now, we can obtain our data from a variety of sources such as databases, web API's but a common way to obtain data is through a good old fashioned file. So in this section, we will use a lot of what we have learnt so far to deal with reading data from and writing to files.

Python can read files pretty easily from the standard library. Its just a case of specifying where the file is and then creating a stream to that location. Let's demonstrate by having a file located in /Path/to/file/test.csv. This is the full path to the comma separated file test.csv.

image

What we have done here is define a string file_name containing the name of the file and then used the open command with the arguments of file_name and ‘r’ which is the mode to read the file in and in this case it refers to read. We have assigned the return of this to the variable f which is a stream to the file. Now to read in the data from the file we simply run:

image

What we get back is the data in a single index list, which isn't that useful. In text files what you find is that lines are separated ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Quick Python Book, Third Edition

The Quick Python Book, Third Edition

Naomi Ceder, David Fugate
Serious Python

Serious Python

Julien Danjou

Publisher Resources

ISBN: 9781119573319Purchase Link