How to write text files in Python 3?

Task:

A very common automation task that we tackle with Python is to create text files as well as read, write and save data into those files.

Solution:

Python delivers very powerful built-in functions to create and manipulate text files. In this short tutorial we’ll go through several key capabilities:

  • Create a new text file from scratch in the current folder.
  • Create a new text file in a different folder.
  • Add text to an existing text file.
  • Writing text line by line into a file.

Let’s look into a couple of examples.

Creating a file in Python with open

To create text files in python, you can use the open(“filename”, “accessmode”) function. The below code will create a file named mydocument.txt with write access permissions. This file will get created under the folder where the code is getting executed. 

Code:

with open("mydocument.txt", mode = "w") as f:
    f.write("This text is written in python")

Note: when opening a file in Write (‘w’) mode, the current file contents will be truncated. Use this mode carefully.

Create a file under a different path:

To create a file under a path different from our working directory, we will have to make a slight change in the way we call the open function.

We’ll use open(r”filepath&name”, “accessmode”). The before the file path ensure that the path name string is read as a raw string. The backslashes in the path will then be treated as literals and not as escape characters. Note that you will need to make sure that the provided directory is available in your operating system before running the code. Let’s take a look.

Code:

with open(r"C:\Temp\mydocument.txt", "w") as f:
    f.write("This text is written in python")

Create a file if doesn’t exist with Python

Below is a bit more robust version of the code in which we’ll first check if the file exists and then we’ll create and write into the file. Note the usage of the pathlib library.

from pathlib import Path

dir_path = Path('C:\Temp')
file_name = 'mydocument.txt'


# check if directory exists
if dir_path.is_dir():
    with open (dir_path.joinpath(file_name),'w') as f:
      f.write("This text is written in python")
    print('File created')
else:
    print('Directory doesn\'t exist')

Append text to an existing file

As mentioned before, the files we created using “w” as access mode will overwrite all existing file contents. Hence we typically open files in append mode (“a”). Append will insert your text after the existing content of your txt file. Let’s take a quick look.

Code:

#write and save

with open(r"C:\Temp\mydocument.txt", "w") as f:
    f.write("This text is written in python")

#read

with open(r"C:\Temp\mydocument.txt", "r") as f: 
   print("New text:\n",f.read())

#append

with open(r"C:\Temp\mydocument.txt", "a") as f:
    f.write("\n This text was added using Append.")


#read the appended text

with open(r"C:\Temp\mydocument.txt", "r") as f:
    print("Append:\n",f.read())

Output:

New text:
 This text is written in python
Append:
 This text is written in python
 This text was added using Append.

Writing a Python file line by line

Let’s now assume that you have a Python list that you would like to write into a file line by line.

Using the writelines() method expects an iterable (such as our list). However, once called writelines() will concatenate the list elements and write write them line by line. Therefore you’ll need a simple loop to append the \n escape character to each element:

languages = [ 'Python', 'Java', 'C#', 'Go', 'R']
file_name = 'languages.txt'

#or use 'a' to append to an existing file
with open (file_name, 'w') as f:
    for item in languages:
        f.write(item + '\n')

The output will be:

Python
Java
C#
Go
R