user13966865
user13966865

Reputation: 468

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

Can anyone explain why the content of the file is being changed while writing?

And how to fix this

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)

The output of the code

#include <iostream>

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

I am using Python 3.8

What I am doing wrong and how can I fix this?

Thank you

Upvotes: 0

Views: 46

Answers (1)

Ajay
Ajay

Reputation: 5347

try changing your string to raw string. Since \n means a new line, you need to use raw strings instead

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.

Upvotes: 2

Related Questions