-1

I have following text in a file:

{"Fn::Base64":{"Fn::Join":["",["#!/bin/bash -ex","\n","echo 'Region name is:'",{"Ref":"AWS::Region"},">>~/user-data.log","\n"]]}}

I'm reading it from file and writing it to a file like:

with open(user_data['file'], "r") as f:
                user_data_script = f.read().splitlines()
lc_arguments['user_data_script'] = user_data_script

But this comes out as:

{\"Fn::Base64\":{\"Fn::Join\":[\"\",[\"#!/bin/bash -ex\",\"\\n\",\"echo 'Region name is:'\",**{\"Ref\":\"AWS::Region\"}**,\">>~/user-data.log\",\"\\n\"]]}}

Notice how it adds \ to each " character. How do I avoid that and why is it doing it?

Blckknght
  • 100,903
  • 11
  • 120
  • 169
Scooby
  • 3,371
  • 8
  • 44
  • 84
  • How are you viewing it to see those slashes? They may not "really" be there since those would be there to escape the quotes so they can be inside other quotes – Eric Renouf Mar 15 '16 at 15:25
  • Also, that looks like you're reading in `json`, why not use the [json](https://docs.python.org/2/library/json.html) module for that instead of treating it like a string? – Eric Renouf Mar 15 '16 at 15:27
  • @EricRenouf this is from a text file so could be anything(is in json format now) , I am viewing it in a file where I write it to through : lc_arguments['user_data_script'] = user_data_script – Scooby Mar 15 '16 at 15:32
  • 1
    Ok, well I maintain that they aren't really there, they're just being printed that way to make the quotes inside the string not terminate the string. You haven't actually shown us any lines that produce output though, so that's still speculation for me at this point. – Eric Renouf Mar 15 '16 at 15:35
  • 2
    @Scooby What do you mean by "comes out as"? Please provide a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) of your problem. – chepner Mar 15 '16 at 16:53

1 Answers1

1

when using the .splitline() method you get a list, and you probably writed the whole list to the file (which somehow caused the problem).

try doing this instead (worked for me):

with open(r'C:\Users\USER\PycharmProjects\untitled\abcd.txt', "r") as f: #in this file i putted your string
   user_data_script = f.read().splitlines()
with open('abcde.txt','w') as f2:
   f2.write(user_data_script[0]) #write the first line and *not* the entire list.

what is writed in abcde.txt is:

{"Fn::Base64":{"Fn::Join":["",["#!/bin/bash -ex","\n","echo 'Region name is:'",{"Ref":"AWS::Region"},">>~/user-data.log","\n"]]}}

hope this help you!!

H T
  • 40
  • 5