我想简单地将函数的输出写入文件,但它返回 None。该函数本身工作得很好,只是打印语句。
#I have reproduced the issue with minimum LOC:
def syl(txt):
for x in text:
print(x)
text = 'example text'
file = 'example'
with open(F"""SYL_{file}""",'a+',encoding='UTF8') as f:
f.write(F'''{syl(text)}''')
content = f.readlines()
print(content)
F'''{syl(text)}'''" #it returns only 'None'.
我也试过:
with open(F"""SYL_{file}""",'a+',encoding='UTF8') as f:
f.write(syl(text)) #str(syl(text)) Doesnt work too, writelines() also changes nothing.
确保函数实际上返回了一些东西(一个没有显式返回的函数,返回None
),打印语句只是出现在控制台上,而不是作为函数的输出被处理。试试这个,使用列表理解:
def syl(txt):
# returns a list of the chars in txt
return [x for x in txt]
现在是写作部分。好吧,事实证明您实际上并不需要调用该函数(您打算用该函数做什么?),只需编写文本:
f.write(text)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句