Working with Files

Let’s look at files now. How to access and write in files using Python.  First will look at text files only, i.e, how to load/open a text file and append or write data.

So, there is an open method.

It is used to read files. It takes arguments (filename, mode). The mode can be :

  1. r -> It is the read mode. In this, you can only read the file can’t manipulate it.
  2. w -> It is the write mode. In this, you can write to file and the current information will be erased.
  3. a -> It opens the file for appending any data written to the file is automatically added to the end.
  4. r+ -> It is both read and write.

The mode argument is optional, by default -: ‘r’

There are two ways of accessing and writing to files. We will walk through examples -:

Another way of creating a file is as follows -:


Checking different methods of a file object

We will see tell(), seek() and how to readlines.

Writing and Appending in files

So, in the end, we appended the data then it will update/ add new content instead of replacing with a new one. So the content in our text file is as follows -:

Test1 Test2

So, this is all for files handling in Python. Hope you enjoyed learning it.


Close Menu