【问题标题】:How to keep the double quotes at the end of a string when using tempfile in python在python中使用tempfile时如何在字符串末尾保留双引号
【发布时间】:2023-02-23 03:57:07
【问题描述】:

在下面的代码中,我有一个用逗号分隔的字符串,该字符串的最后一个值为“”。当我使用下面的代码将其写入临时文件时,双引号被删除。我怎样才能阻止这种情况发生?

导入临时文件 导入操作系统

fd, 路径 = tempfile.mkstemp()

以 os.fdopen(fd, 'w') 作为 tmp: tmp.write("abc,123,""")

【问题讨论】:

  • 看起来您希望在字符串中输入两次 " 可以将其转义。您应该使用 \" 而不是 ""。

标签: python temporary-files


【解决方案1】:

要保留双引号,您需要用单引号将其括起来。

import tempfile import os

fd, path = tempfile.mkstemp()

with os.fdopen(fd, 'w') as tmp: 
    tmp.write('abc,123,""')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2019-09-12
    • 2021-09-28
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 2012-11-21
    相关资源
    最近更新 更多