# Reading Files to Strings using Python and then Loading them to JSON

DevFeed: [Reading Files to Strings using Python and then Loading them to JSON](<https://devfeed.tech/articles/reading-files-to-strings-using-python-and-then-loading-them-to-json-28225.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/python/2019/11/04/reading-files-to-strings-using-python.html>)

Author: Fuzzygroup

Published: 2019-11-04T00:00:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Python](<https://devfeed.tech/topics/python.md>), [JSON](<https://devfeed.tech/topics/json.md>), [import](<https://devfeed.tech/topics/import.md>)

Tags: [files](<https://devfeed.tech/tags/files.md>), [import](<https://devfeed.tech/tags/import.md>), [json](<https://devfeed.tech/tags/json.md>), [python](<https://devfeed.tech/tags/python.md>)

## AI overview

A concise Python tutorial showing several ways to read file contents into a string, including context managers, pathlib, and explicit closing. It also demonstrates passing the resulting text to json.loads to create a Python dictionary.

## Source excerpt

I know this is dirt simple but I'm writing it down because it is one of those simple things that I just forget constantly. In each of these cases, the output is to the str variable. Using a With Block to Auto Close the File As a rubyist, I keep reading this as str is local to the with "block". Of course python doesn't have blocks ... with open('data.txt', 'r') as myfile: str = myfile.read() Python 3.5 Path Statement One Liner I really like this approach but pathlib always has to be imported. from pathlib import Path str = Path('data.txt').read_text() Non Auto Closing Not Recommended This is simple but leaves an open file hanging around. Sigh. str = open('jsons/gab_02.json', 'r').read() Auto Closing Single Line This is elegant but it buries the assignment variable in the middle of the line which feels wrong. _ = open('jsons/gab_02.json', 'r'); str = _.read(); _.close() Loading it to JSON The json.loads statement takes a string in and converts it to a Python dict / hash so all you need to do is inline the string reading call from above and get an easy one liner (if you disregard the import lines). from pathlib import Path import json gab = json.loads(Path('jsons/gab_02.json').read_text()) References Stack Overflow Real Python