我创建的函数不能将结果保存到文本文件中。

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

我们有一个练习,其中我们被告知将摄氏度转换为华氏度,并将结果保存在一个新的文本文件中,但我没有得到结果保存在文本文件中。

下面是代码:-

temperatures=[10,-20,-289,100]
file = open("temperature_result.txt",'w')
def c_to_f(c):
    f=c*9/5+32
    for t in temperatures:
        return((c_to_f(t))
    file.write(str(c_to_f(t)))
file.close()

我在终端得到这个错误:-

File ".\python_to_ttx.py", line 7
    file.write(str(c_to_f(t)))
       ^
SyntaxError: invalid syntax
python syntax syntax-error
2个回答
2
投票

试试这段代码

temperatures=[10,-20,-289,100]
file = open("temperature_result.txt",'w')
def c_to_f(c):
    f=c*9/5+32
    return f
for t in temperatures:
    file.write(str(c_to_f(t)))
file.close()

2
投票

你应该使用 with 方法。

def c_to_f(c):
    f = c * 9 / 5 + 32

    return f


def write_file(file, temperatures):
    with open(file, 'w'):
        for t in temperatures:
            file.write(str(c_to_f(t)))
        file.close()


temperatures = [10, -20, -289, 100]
file = "temperature_result.txt"

write_file(file, temperatures)
© www.soinside.com 2019 - 2024. All rights reserved.