Python

How to Read and Write Text Files in Python

This article will cover a guide explaining external file handling in python. The main focus will be on opening and closing of text and other non-binary data files stored on a storage media, allowing you to run various operations on contents of the opened files.

Opening and Closing of a File

To read data from a text file named “data.txt”, you need to use the “open” method that comes with official Python builds. Check the sample code below:

f = open('data.txt', 'r')
f.close()

The first statement opens the “data.txt” file in “r” (read-only) mode. The “open” method accepts a filename and the mode for handling the file as arguments. Besides “r” mode, there are other modes as well that will be explained later. The code snippet above does not run any operations on the opened file. The “close” method is used to close the opened file cleanly so that memory can be freed and to avoid data corruption in the opened file that can happen sometimes if the file is not closed properly.

Instead of using the “open” method to handle opening and closing of files, you can combine it with “with” keyword and use “with open” statement.

with open('data.txt', 'r') as f:
    pass

The main advantage of using a “with open” statement is that the interpreter automatically closes the opened file safely when “with open” code block is parsed completely. Though garbage collector in Python automatically closes opened files after a while as per preset rules, “with open” statements ensure that file is cleanly closed as soon as the code block is finished to free up resources.

Reading Lines of a Text File

To read contents of a file, use the code sample below:

with open('data.txt', 'r') as f:
    data = f.read()
print (data)

For instance, if “data.txt” file has 1-10 numbers, each on a new line, you will get following output after running the above code:

The entire data dump of the “data.txt” file is stored in the “data” variable. If you want to read lines to a list, you can use following code samples:

with open('data.txt', 'r') as f:
    data = f.readlines()
print (data)
with open('data.txt', 'r') as f:
    data = list(f)
print (data)

Note that using above snippets may get you the “\n” (newline) character at the end of each element in the list. To remove these newline characters, you may have to loop through the list. You can both create a new list and strip newline characters by using following code instead:

data_list = []
with open('data.txt', 'r') as f:
    for line in f:
        data_list.append(line.strip())
print (data_list)

Running the code above will get you following output:

Writing Data to an Opened File

To write data to a file being opened using the “with open” statement, you will have to supply a different opening mode as argument. Here are some of the modes:

  • ‘a’ – used for appending data at the end of an opened file, creates new file if it doesn’t exist
  • ‘w’ – erases contents of opened file and writes new data, creates new file if it doesn’t exist
  • ‘r’ – read-only mode (default mode if no argument is supplied)
  • ‘r+’ – used for both reading and writing (initial position is at the beginning of the file)
  • ‘b’ – file is opened in binary mode (useful for non-text binary files), can be combined with other modes
  • ‘a+’ – used for reading and appending, creates a new file if it doesn’t exist
  • ‘w+’ – used for reading and writing, creates a new file if it doesn’t exist

Some code snippets using different modes to write data are listed below.

To write new content to a text file while erasing existing data, use the following sample:

with open('data.txt', 'w') as f:
    f.write("1\n2")

After running the snippet above, 1-10 numbers in the “data.txt” file should be replaced by two new lines.

To add lines at the beginning of a text file, you need to use “seek” method to go back to the starting position of the file buffer:

with open('data.txt', 'r+') as f:
    data = f.read()
    f.seek(0)
    f.write("-1\n0\n")
    f.write(data)

After running the snippet above, -1 and 0 numbers will be added to the top two lines in “data.txt” files.

To append data at the end of the file, use the following sample:

with open('data.txt', 'a') as f:
    f.write("11\n12")

After running the snippet above, 11 and 12 numbers will be added at the end of the file.

Conclusion

Built-in classes and methods in Python provide a robust way to handle text files. With only a few lines of code you can manipulate existing data in a file as well as insert new lines.

About the author

Nitesh Kumar

I am a freelancer software developer and content writer who loves Linux, open source software and the free software community.