file.write没有输出。[关闭]

问题描述 投票:0回答:2

我运行以下程序,希望将输出保存为.txt文件。

我已经在python 3.6的spyder IDE中运行了它。

temperatures = [10,-20,-289,100]

file = open('temperature.txt','w')

def f_to_c(temperatures):
    for celsius in temperatures:
        if  celsius >  -273.15:
            fahrenheit = celsius * (9/5) + 32
            file.write(str(fahrenheit))

f_to_c(temperatures)

此代码中有无错误消息,但是在.txt文件中没有得到输出。你能帮忙吗?

python python-3.x
2个回答
1
投票

更新的功能和说明:

def f_to_c(file: str, temps: list):
    with open(file, 'a', newline='\n') as f:
        for temp in temps:
            if  temp >  -273.15:
                fahrenheit = temp * (9/5) + 32
                f.write(f'{fahrenheit}\n')


temps = [10,-20,-289,100]
f_to_c('temperature.txt', temps)

或者:

  • 具有用于转换温度的专用功能。
    • 这是处理任务的适当方法。
    • 函数应该做一件事。
  • 单独处理文件
def f_to_c(temps: list) -> list:
    return [temp * (9/5) + 32 for temp in temps if temp > -273.15]


temps = [10,-20,-289,100]
with open('temperature.txt', 'a', newline='\n') as f:
    for value in f_to_c(temps):
        f.write(f'{value}\n')

0
投票

下面更清洁的方法

return
© www.soinside.com 2019 - 2024. All rights reserved.