Best Practice to Save Python String to File Safely – Python File Operation Tutorial

By | October 9, 2019

To save python string to a file in python safely, there are somthing you should notice:

1.The encoding of this string

2.Be sure the string has been saved

In this tutorial, we will introduce and write an example to show how to save python string to a file safely, you can use our this example in your applications safely.

The encoding of this string

String can be encoded by different content types, such as utf-8, gbk or gb2312. To save this string, you should know the encoding type of this string, otherwise,  the save operation will be failed.

Fix Python File Write Error: UnicodeEncodeError: ‘gbk’ codec can’t encode character – Python Tutorial

Be sure the string has been saved

To be sure the string has been saved into a file, you should process any errors when saving, otherwise, this operation will been blocked.

Write an example to save file correctly

We define a python function to save a file. It is:

def save_to_file(file_name, contents, encoding="utf-8"):
    
    fh = None
    ok = False
    try:
        fh = open(file_name, 'w', encoding)
        fh.write(contents)
        ok = True   
        print("save ok!", flush = True)
    except IOError as e:
        print(e)
        ok = False
        print("save fail!", flush = True)
    finally:
        #print(type(fh))
        try:
            if fh:
                fh.close()
        except:
            ok = False
    return ok

How to use this funciton?

file_name: the name of file

contents: the python strin should be saved into file_name

encoding: the encoding of contents

Leave a Reply