Tutorial - Python 3 basics
Writing and reading from files

Posted October 18, 2018 by Rokas Balsys



In this tutorial we're going to cover the basics of working with files, how to write data to them and how to read data from them. Python provides a 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 to 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 that contains the name of the file that you want to access.
  • access_mode − The access_mode determines the mode in which 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 optional parameter and the default file access mode is read (r).
  • buffering − If buffering value is set to 0, no buffering takes place. If 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 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.
  • a - 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 your self.
So lets 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 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 count in "read()" brackets is missing, then it tries to read as much as possible until the end of file.


Write from the end of 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 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 file:

Sometimes when we want to edit file, we don't want to delete everything or append to existing file, maybe we want to insert few sentences in a middle of text somewhere, in this case we need to change 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 file.

The tell method tells you the position of pointer within the file.
Here is same example where we insert 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 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 indise of them. Now we can move to next tutorial: