【问题标题】:How to write file paths to a txt file in Python如何在 Python 中将文件路径写入 txt 文件
【发布时间】:2020-09-26 05:13:24
【问题描述】:

我正在尝试在 Python 中将多行写入文本文件

with open('output.txt', 'w') as outfile:
    outfile.write("open\n" +
                  "c:\files\file.scr"+
                  "close"
                 )

文件路径写不正确,

   open
    c:iles\drawing.dwgclose

有人可以建议如何编写文件路径吗?

【问题讨论】:

    标签: python-3.x file


    【解决方案1】:

    你可以通过在前面添加r来制作字符串raw

    with open('output.txt', 'w') as outfile:
        outfile.write("open\n" +
                      r"c:\files\file.scr"+
                      "close"
                     )
    

    【讨论】:

      【解决方案2】:

      你必须在字符串中转义 \

      with open('output.txt', 'w') as outfile:
          outfile.write("open\n" +
                        "c:\\files\\file.scr"+
                        "close"
                       )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-24
        • 1970-01-01
        • 2016-02-24
        相关资源
        最近更新 更多