【问题标题】:F-Strings and writing function output to file in python3F-Strings并将函数输出写入python3中的文件
【发布时间】:2019-02-01 15:34:01
【问题描述】:

我只想将函数的输出写入文件,但它返回 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.

【问题讨论】:

  • f-string 的使用对我来说似乎很好,只是syl 没有返回任何东西,readlines()write() 之后是没有意义的(之前做一个f.seek(0) !)

标签: python-3.x function file-writing


【解决方案1】:

确保函数确实返回一些东西(一个没有显式返回的函数,返回None),打印语句只是出现在控制台上,而不是作为输出处理功能。试试这个,使用列表推导:

def syl(txt):
    # returns a list of the chars in txt
    return [x for x in txt]

现在是写作部分。好吧,事实证明你实际上不需要调用函数(你打算用函数做什么?),只需编写文本:

f.write(text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 2015-01-21
    • 2020-07-03
    • 2018-09-09
    • 1970-01-01
    相关资源
    最近更新 更多