You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3如何使用f-string正确写入多行内容到文件 规避语法错误

问题解决方法

错误根源

  • 第一个SyntaxError: invalid syntax报错是因为f-string会自动解析所有{}包裹的内容为Python表达式,你配置内容里的{print $1}不是合法Python语法,直接触发解析报错。
  • 第二个f-string expression part cannot include a backslash报错是Python f-string的固有语法限制:大括号内部的表达式不允许出现反斜杠。

解决方法

情况1:配置内容不需要插入Python变量

直接删除字符串开头的f,使用普通三重引号字符串即可,所有符号都会原样输出,不会触发任何解析逻辑,修改后的代码如下:

def create_testfile(self) -> None:
    """writes the config file 
    """
    value = """ #==================================
## NAT network DHCP params configuration
bridge=$(ifconfig | grep  "flags" | awk -F : '{print $1}' | sed '/lo/d' | sed '/vif/d')
echo "${command}"
case "${command}" in
    online)
...
...
...
        port_num_check
esac
"""
    with open("network.txt", "w") as network:
        network.write(value)

普通三重引号字符串中可以正常添加\n等转义字符,不会触发报错。

情况2:配置内容需要插入Python变量

  • 所有不需要解析、需要原样输出的大括号,用双大括号{{}}转义,比如{print $1}改成{{print $1}}
  • 反斜杠不要放在f-string的{}内部,换行符可以直接写在字符串的普通区域,或者预先定义为变量再放到{}中。
    示例代码如下:
def create_testfile(self) -> None:
    """writes the config file 
    """
    # 示例:需要插入的Python变量
    custom_port = "8080"
    value = f""" #==================================
## NAT network DHCP params configuration
bridge=$(ifconfig | grep  "flags" | awk -F : '{{print $1}}' | sed '/lo/d' | sed '/vif/d')
echo "${{command}}"
case "${{command}}" in
    online)
    port={custom_port}
...
...
...
        port_num_check
esac
"""
    with open("network.txt", "w") as network:
        network.write(value)

内容的提问来源于stack exchange,提问作者Kiran ND

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 15:39:03