In this article you’re going to learn how to work with files in Python, you gonna learn various techniques on how open, read, manipulate, and save files in python.

Once you finish this article you will be in a good position of handling files in python so I suggest you read this to the end.

Getting started

Working with files in python is straightforward, you can open files and read it in just one line of code.

For instance, let’s try reading quotes.txt from a file

True humility is not thinking less of yourself; it is thinking of yourself less.
I believe in Christianity as I believe that the sun has risen: not only because I see it, but because by it I see everything else.
You are never too old to set another goal or to dream a new dream.

Reading from file

>>> data = open('quotes.txt').read()
>>> print(data)
True humility is not thinking less of yourself; it is thinking of yourself less.
I believe in Christianity as I believe that the sun has risen: not only because I see it, but because by it I see everything else.
You are never too old to set another goal or to dream a new dream.

We used the open ( ) function to read a file in python in just one line of code.

Modes of opening files in Python

You can open a file in python in different modes such as reading mode, writing mode, appending mode, binary mode and etc.

By default, python opens the files in reading mode thus why in the example above we didn’t specify the mode but it doesn’t throw any error.

We use the following abbreviation to specify the mode;

  • r -> for opening file in reading mode
  • w ->for opening file in writing mode
  • a -> for opening file in appending mode
  • r+ ->for opening file in reading and writing mode
  • w+ ->for opening file in writing and reading mode
  • rb -> for reading in binary mode
  • wb -> for writing in binary mode

#python #web-development #programming #developer #machine-learning

How to Work with Files in Python
2.25 GEEK