【问题标题】:Keep the new line symbols in the string when writing in a text file Python写入文本文件Python时保留字符串中的换行符
【发布时间】:2015-05-11 15:39:23
【问题描述】:

我有一个字符串列表,其中一些字符串包含'\n'。我想将此字符串列表写入一个文本文件,然后稍后再将其读回并使用readlines() 将其存储到一个列表中。我必须保留原文;意思是不从文本中删除新行。

如果我不删除所有这些新行,那么readlines() 当然会返回比原始列表更多的字符串。

我怎样才能做到这一点?或者真的没有办法,我应该改写其他格式。谢谢。

【问题讨论】:

  • 你可以写字符串'repr,然后在读回它们时写eval(或ast.literal_eval)这些行......或者只是用一些“魔术字符串”替换换行符,比如'NEWLINE'
  • 您可以使用 \ 本身是一个转义字符这一事实,因此 \\n 将写作 \n
  • @SuperBiasedMan - 但它不再是换行符了。
  • @blue482 - 您是否试图保持列表边界? picklejson 将是不错的选择。
  • @SuperBiasedMan 我仍然不确定 OP 想要什么!

标签: python io newline


【解决方案1】:

以下内容:

from __future__ import print_function
strings = ["asd", "sdf\n", "dfg"]
with open("output.txt", "w") as out_file:
  for string in strings:
    print(repr(string), file=out_file)
with open("output.txt") as in_file:
  for line in in_file:
    print(line.strip())

打印

'asd'
'sdf\n'
'dfg'

要正常打印(不带引号),可以使用ast.literal_eval:print(ast.literal_eval(line.strip()))

【讨论】:

    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2010-11-11
    • 1970-01-01
    相关资源
    最近更新 更多