You can yield from dictionary loaded using JSON, iterating over key-value pairs in a dict, but that would not be your desired behavior.
def tFileRead(fileName, JSON=False): with open(fileName) as f: if JSON: yield from json.load(f).items()
It would be nice if you could just return the generator, but this will not work, since with the help, the file is closed as soon as the function returns, i.e. before the generator is consumed.
def tFileRead(fileName, JSON=False): with open(fileName) as f: if JSON: return json.load(f) else: return (line.rstrip('\n') for line in f)
Alternatively, you can define another function only to get lines from a file and use this in a generator:
def tFileRead(fileName, JSON=False): if JSON: with open(fileName) as f: return json.load(f) else: def withopen(fileName): with open(fileName) as f: yield from f return (line.rstrip('\n') for line in withopen(fileName))
But once you're there, you can simply use two separate functions to read the en-block file as JSON or to iterate over the lines ...
source share