Tutorial - Python 3 basics Writing and reading from files

In this tutorial we will learn how to use Python modules. A module can define functions, classes and variables which include runnable code.

In this tutorial, we will cover the basics of working with files, how to write data to them, and how to read data from them. Python provides the basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object. Before you can read or write a file, you must open it using Python's built-in open() function.

The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.

Syntax:

file object = open(file_name [, access_mode][, buffering])

Here are syntax details:

  • file_name − The file_name argument is a string value containing the name of the file you want to access.
  • access_mode − The access_mode determines the mode in which a file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the list. This is an optional parameter and the default file access mode is read (r).
  • buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior). Default buffer size you can check with the following code:
    import io
    print(io.DEFAULT_BUFFER_SIZE)
    Result is: 8192.

Here is a list of the different modes for opening a file:

  • r - Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
  • rb - Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file.
  • r+ - Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
  • rb - Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
  • wb - Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
  • w+ - Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
  • wb+ - Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
  • - Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
  • ab - Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
  • ab - Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
  • a+ - Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
  • a+ - Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

write() to file method:

The write() method writes any string to an open file. It is important to note that write() method does not add a newline character ('\n') to the end of the string, you need to do it yourself.
So let's start with an example:

# At first we must open file
file = open("write_tut.txt", "w")
# Write anything you want
file.write( "This is python write to file tutorial.\nWe will learn it!\n")
# Always close file
file.close()

The above method would create a write_tut.txt file and would write given content in that file and finally, it would close that file. Now you can open that file and check it out.

read() from file method:

The read() method reads a string from an open file. It is important to note that Python strings can have binary data.
Continue with an example:

# At first we must open file
file = open("write_tut.txt", "r")
# Read everything from file and print
print(file.read())
# Always close file
file.close()

This method starts reading from the beginning of the file and if the count in "read()" brackets are missing, then it tries to read as much as possible until the end of the file.

Write from the end of the file:

Now we get to appending a file in python. If you will try writing to file it will clear the file and write to it just the data you specify in the write operation. But when using appending Python will simply take what was already there, and add the new data to it, simply talking we will move the file pointer to the end of the file.
Continue with an example:

# At first we must open file using "a"
file = open("write_tut.txt", "a")
# Add anything you want
file.write( "This is python write to file tutorial with append.\nWe now know how it works!\n")
# Always close file
file.close()

While running this code if write_tut.txt already exists, the new lines will be added to it. If that file does not exist, then it will be created.

Pointer positioning in the file:

Sometimes when we want to edit a file, we don't want to delete everything or append to an existing file, maybe we want to insert few sentences in the middle of the text somewhere, in this case, we need to change the pointer so we are using tell and seek(offset, 0) methods.

The seek(offset, 0) method changes the current file position. The offset argument indicates the number of bytes to be moved from the beginning of the file.

The tell method tells you the position of the pointer within the file.
Here is the same example where we insert a new line into text:

# Open a file
file = open("write_tut.txt", "r+")
# Read a file
string = file.read()
print ("Read String is:", string)
# Check current position
position = file.tell()
print ("Current file position:", position)
# Reposition pointer where we need
position = file.seek(55,0)
# Read string from pointer
string2 = file.read()
# Reposition pointer again
position = file.seek(55,0)
# Write new line and add string2 
file.write("\nInserting new line to text."+string2)
# Check if everything worked
file.seek(0,0)
print ("\nFull string:", file.read())
# Close opened file
file.close()

And here is produced a result:

Read String is: This is python write to file tutorial.
We will learn it!
This is python write to file tutorial with append.
We now know how it works!
Current file position: 134

Full string: This is python write to file tutorial.
We will learn it!
Inserting new line to text.
This is python write to file tutorial with append.
We now know how it works!
>>> 

In this tutorial, we covered how to read files and how to modify text inside of them.