你可以yield from
裝載JSON,從而遍歷的字典鍵 - 值對的字典,但是這不會是你想要的行爲。
def tFileRead(fileName, JSON=False):
with open(fileName) as f:
if JSON:
yield from json.load(f).items() # works, but differently
for line in f:
yield line.rstrip('\n')
這將是很好,如果你可以只返回一個發電機,但是這是不行的,因爲使用with
,發電機被消耗之前的文件,一旦封閉,函數返回時,即。
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) # won't work
或者,你可以定義另一個函數只是從文件中產生的線條和使用發電機:
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))
但是,一旦你在那裏,你真的可以只使用兩個單獨的功能用於讀取文件en-block爲JSON或迭代行...
如果不是JSON嘗試返回一個生成器的閉包 – Aaron
單個函數必須返回或返回。不是 – Aaron
你可以從'json.load'產生,但這隻會產生字典中的密鑰。您如何計劃在這兩種情況下使用該功能? –