-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?

  • 1
    Write your text in a multi-line string and write that one string. – quamrana Mar 10 '22 at 14:11
  • If you don't want to use a multiline string: https://stackoverflow.com/questions/1874592/how-to-write-very-long-string-that-conforms-with-pep8-and-prevent-e501 – Tzane Mar 10 '22 at 14:23
  • @Tzane This has nothing to do with writing to files and will not add new line characters... – Tomerikoo Mar 10 '22 at 14:24

2 Answers2

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
TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
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)
Furkan Ozalp
  • 334
  • 1
  • 4
  • 7