How to write a Python string to a file?

Writing a string to a text file with Python3

The file object write() Python method, allows to add string text values to already opened text and csv files. The writelines() method allows to write a list made of string elements into the already opened files.

#1 Save a string to a file

Let’s start by defining the following string and string of strings

lang_str = 'Python is a very popular language for Data Analysis.'
lang_lst = ['\nR ','\nGo','\nPython', '\nJulia']

We will first go ahead and define a path to our file:

import os
dir_n = r"C:\WorkDir"
file_n = "my_file.txt"
file_path = os.path.join(dir_n , file_n)

Now that the file object has been created, we’ll open it for write (‘w’) access and add the text:

with open (file_path, 'w') as my_file:
    my_file.write(lang_str)

#2 Append a string to an existing file

In the previous example, we have created the file and then added the string text. We can obviously append text to an existing file, by accessing it in append(‘a’) mode:

with open (file_path, 'a') as my_file:
    my_file.write(lang_str)

The appended text will be added in a new line at the end of the file.

#3 Write a json string to a file

Let’s assume that a json string:

j_string = {
	"area": "Python",
	"skill": "Data Engineer",
	"salary": 134
}

We can add the string to a json file in our file system using the following code:

import json

#define the path for your json file
j_path = r'C:\WorkDir\small_j.json'

# open your json file and add the json string
with open (j_path, 'w') as j:
    json.dump(j_string, j)

#4 Write string to a binary file

If we have an encoded string, we can write it as bytes into a file:

import os

bin_data = '\44\455aef'.encode('UTF-8')
dir_n = r"C:\WorkDir"
file_n = "my_bin_data.txt"
file_path = os.path.join(dir_n , file_n)

with open (file_path, 'wb') as my_bin_file:
    my_bin_file.write(bin_data)

#5 Add list to text file

As previously mentioned, the file object writelines() method allows us to easiliy add a list of strings to our file:

with open (file_path, 'a') as my_file:
    my_file.writelines(lang_lst)

Related learning:

How to add a list to a csv comma separated values file?