How to read and write files

Reading and writing files in Python is really easy since you don’t need to import a library – everything needed is already built in.

Let’s start with creating a file. To create a file in Python, we need to create a file object. A file object contains attributes and methods that can be used to manipulate the specified file. This is done with the following statement:

fw = open('test.txt', 'w')

Let’s break down the syntax above:

  • fw – the name of the variable to which the file object will be added.
  • open(‘test.txt’, ‘w’) – the open function takes two parameters:
    • test.txt – the name of the file we would like to open. If the file doesn’t exist, it will be created.
    • mode – the way in which the file will be used. The possible values are:
      • r – Read mode, used when you only need to read the contents of the file.
      • w – Write mode, used to edit and write new information to the file.
      • a – Append mode, used to add new data at the end of the file.
      • r+ – Special read and write mode, used to handle both actions when working with a file

So, the statement fw = open(‘FILENAME’, ‘w’) creates a file object and prepares it for writing text to it. If you execute the code now, an empty file should be created in the same directory in which your script is stored.

To write some text to the file we’ve just created, we can use the following code:

fw.write(‘Some text’)

If no path is specified, the file will be created in the same directory the Python script is in. If a file already exists, it will be overwritten.

 

So the following code will create a file object, prepare it for writing, and write two lines of text int it:

fw = open('new_file.txt', 'w')
fw.write('Have a nice day!\n')
fw.write('You too!')

After we’ve finished working with a file, we need to close the file object to free its memory. To to this, we use the close() method:

fw.close()
Geek University 2022