如何跳过字符串中的换行,除非将其写入文件中?

2024-05-19 12:35:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在考虑如何跳过字符串中的任何新行,并将该字符串作为一行写入python3中的文件

例如:

stringValue = "This\nis\nmy\nstring"
file = open(filepath, 'a+')
outmessage = "\ntimestamp\nlength\n" + stringValue
file.write(outmessage)

  • 时间戳、长度和stringValue都应该写在文件中的3行中
  • 但是,stringValue在文件中被写成四行,这是我不想要的

打开文件并指定新行字符时,我试图给出newLine参数:

stringValue = "This\nis\nmy\nstring"
file = open(filepath, 'a+', newline='\r\n')
outmessage = "\r\ntimestamp\r\nlength\r\n" + stringValue
file.write(outmessage)

但是,这个解决方案似乎不起作用

我需要换行符出现在stringValue中,以便在从文件读取后的稍后阶段对其进行解码


Tags: 文件字符串openthispython3filewritenis
1条回答
网友
1楼 · 发布于 2024-05-19 12:35:59

用不应出现在实际文本中的distinc字符串替换换行符

outmessage = "\ntimestamp\nlength\n" + stringValue.replace("\n", "*newline*")

然后,在读取文件时,可以用\n替换*newline*以返回换行符

相关问题 更多 >