为什么 file.write() 修改 Python 中文件的内容

Why file.write() modifying the content of file in Python

谁能解释一下为什么文件内容在写入时被更改?

以及如何解决这个问题

c='''#include <iostream>

int 
main ()
{
  std::cout << "Hello, world!\n"; <== this line is getting changed in output
  return 0;
}
'''
with open('x.cpp','w+') as f:
    f.write(c)

代码的输出

#include <iostream>

int 
main ()
{
  std::cout << "Hello, world!
"; <= modified while doing write operation
  return 0;
}

我正在使用 Python 3.8

我做错了什么,我该如何解决?

谢谢

尝试将您的字符串更改为 raw 字符串。由于 \n 表示换行,因此您需要使用原始字符串

c=r'''#include <iostream>

int 
main ()
{
  std::cout << "Hello, world!\n"; <== this line is getting changed in output
  return 0;
}
'''

Lexical Analysis

Unless an 'r' or 'R' prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C.