How to write text files in Python 3?

Create text files using Python

To create text files in Python, use the open built in function with two key parameters: the file path and the mode in which the file should be opened. Use ‘w’ as the mode value to open the file for writing. Once the file is opened, call the write() build-in function and add text to the file. Here’s code that you can use to write a new text file in Python:

With open (txt_file_path, 'w') as text_file:
    text_file.write("Your text here")

Writing text files with Python – Detailed example

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, we typically use a With block and 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 your Python script is saved.

Code:

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

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

Create a file in a different directory 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 will first make sure that file directory path is available in your operating system. We’ll then use a With context to open the file in Write access mode and append a string to the file. Let’s take a look at the snippet – Note the usage of the pathlib library (available from Python 3.4) that simplifies file object handling in Python.

Code:

from pathlib import Path

# replace with your preferred directory path
dir_path = Path('C:\Temp')
file_name = "mydocument.txt"
file_path = dir_path.joinpath(file_name)

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

A similar implementation using the Python standard library os module (also available earlier than Python 3.4):

import os

# replace with your preferred directory and file path
dir_path = r"C:\Temp"
file_name = "mydocument.txt"
file_path = os.path.join(dir_path, file_name)
# check if the directory exists
if os.path.exists (dir_path):
    # create the file
    with open(file_path, "w") as f:
        f.write("This text is written with Python.")
        print('File was created.')
else:
    print("Directory doesn\'t exist.")

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 directory and file paths exists before reading and writing into the file.

from pathlib import Path

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

# check if directory exists
if dir_path.is_dir():

    # check if file already exists
    if file_path.is_file():
        print('File already exists.')
    else:
        with open (dir_path.joinpath(file_name),'w') as f:  
            f.write("This text is written with Python.")
            print('File was created.')
else:
    print('Directory doesn\'t exist, please create the directory first.')

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 text 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 with 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 with Python.
Append:
This text is written with 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.

The file object writelines() method expects an iterable (such as our list). However, once called writelines() will concatenate the list elements and write them into the file. If you need to write line by line, you can loop through the list elements, append the \n escape character to each element and write them into the file as shown in the snippet below:

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

Follow up learning:

How to save a Numpy array to a text file?