我运行以下程序,希望将输出保存为.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文件中没有得到输出。你能帮忙吗?
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)
with open
,仅在调用函数时打开文件。file
从未关闭。with
,将自动关闭文件。 Reading and Writing Filesfile
对象。 Scope of Variables in Pythona
附加到文件。f'{fahrenheit}\n'
是f-string。fahrenheit
转换str()
(file: str, temps: list)
使用PEP 484 - Type Hintsdef 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')
下面更清洁的方法
return