简体   繁体   中英

Not able to add new line in file

I am trying to write to a file using these functions:

json_decode = json.loads(any_content)
json_decode = byteify(json_decode)

After some processing of the any_content, I extract specific tags of JSON to script1 and scriptOrigin .

script1 = json.dumps(script1)
script2 = []
    for i,j in scriptOrigin:
        j = "#" + j + "\n"
        script2.append(j)

I want to use these to write to path1 .

def function(script1, path1, script2):
   writeArrayToFile(script1, path1, "a")
   writeToFile("\n", path1, "a")
   writeToFile(script2, path1, "a")

def writeToFile(content, path, mode, breakBy=None):
  try:
     print "content is: " 
     print content
     print type(content)

     outputFile = open(path, mode)

     try:
        if breakBy:
            outputFile.write(content + breakBy)
        else:
            outputFile.write(content)
        outputFile.close()

     except IOError as e:
       print 'Trouble writing to file'

  except IOError as e:
     print 'Trouble opening file'

def writeArrayToFile(array, path, mode):
  for item in array:
      item = "\n" + item + "\n"
      writeToFile(item, path, mode, "\n")

I want the script to output something like this:

123
abc
etc

However, what I get is this:

123abcetc

When I print out the strings, they do show up with lots of newlines. However when it comes to the content of the file, it becomes one line.

I have tried different default applications for the file that is being edited -- I have tested Visual Studio, WordPad, and NotePad, but they all did not make a difference.

I have also tried to add in \\r\\n instead of simply putting \\n . This made no difference either.

I had an extra json.dumps(any_text) that made everything, even lines that had \\r\\n to one line.

So for example a\\r\\n1 will be processed as:

a
1

However if the text was taken to be processed again, it then became:

a1

Thanks for all the help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM