我目前正在使用python Crashcourse学习Python。我的问题涉及练习10-4 (留言簿)。我试图弄清楚为什么我的代码不能工作(我得到一个语法错误)。我的代码与书中的代码几乎完全相同。
我的版本:
with open(filename, 'a') as file_object:
file_object.write(file_object"{name}\n")
print(file_object"Hi {name}, you've been added to the guest book.")
这本书的内容是:
with open(filename, 'a') as f:
f.write(f"{name}\n")
print(f"Hi {name}, you've been added to the guest book.")
我知道我所要做的就是将file_object
缩短为f
,它会工作的,但我的问题是为什么file_object
不工作?它不是像f
一样只是一个变量吗?为什么长度很重要?
发布于 2020-08-16 09:12:31
出于教程目的,这是crashcourse上的一个很差的示例。作为文件句柄的文件名的f与作为格式说明符的write/print行中的f不同。
with open(filename, 'a') as file_object:
file_object.write(f"{name}\n")
print(f"Hi {name}, you've been added to the guest book.")
https://stackoverflow.com/questions/63432164
复制相似问题