Python Read/Write Single Large String to File

October 19, 2019

Write string to file

import os

file_path = ...
content = 'LARGE STRING'

# optional - make sure dir exist
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'wb') as f:
    f.write(content)

Read string from file

# optional - check file exist
if os.path.exists(file_path):
    with open(file_path, 'rb') as f:
        content = f.read()
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.