-1

I want to write some block of text to .txt file.

example I am having text like:

" <?xml version=\"1.0\" encoding=\"utf-8\"?>
  ParameterAllocation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                 xmlns="CGenCorrXSD_V1">  "

how can I write this text block into .txt file using python.

If I use File_name.write("--") it will write only single line and I have to use "\n" for every new line. I want to preserve same indentation format as well.

any easy method exists?

3
  • 1
    Write your text in a multi-line string and write that one string. Commented Mar 10, 2022 at 14:11
  • If you don't want to use a multiline string: stackoverflow.com/questions/1874592/… Commented Mar 10, 2022 at 14:23
  • @Tzane This has nothing to do with writing to files and will not add new line characters... Commented Mar 10, 2022 at 14:24

2 Answers 2

2

You probably need to use """ instead of " such as what follows:

myData = """ <?xml version=\"1.0\" encoding=\"utf-8\"?>
  ParameterAllocation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                 xmlns="CGenCorrXSD_V1">  
"""
# The rest of the code which saves `myData` into a file
Sign up to request clarification or add additional context in comments.

Comments

0

use """ for multi lines as follows:

  Textdata = """ <?xml version=\"1.0\" encoding=\"utf-8\"?>
      ParameterAllocation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                     xmlns="CGenCorrXSD_V1">  """
    
    with open("Text.txt","w") as file:
        file.write(Textdata)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.