Search code examples
pythonstringfileubuntuediting

Python: How to Add Specificly Characterized text To A Text File


I am writing a program using the Python Programming Language. Here is a part of my python script:

#!/usr/bin/python

import os
import time
import sys

print "Creating new text file"
file = open("launcher_profiles.json",'w')
file.write('{
  "profiles": {
    "MODS 7.10": {
      "name": "Forge",
      "lastVersionId": "mods7.10"
    },
    "Forge": {
      "name": "Forge"
    },
    "mods": {
      "name": "mods",
      "lastVersionId": "mods"
    }
  },
  "selectedProfile": "Forge",
  "clientToken": "e1a07b41-8e41-44b5-9781-3dd3a201bf30",
  "authenticationDatabase": {
    "6d63772c9c4141e2908049dd833d9cc4": {
      "username": "Marc",
      "accessToken": "df914be0efcc4f16aedb532d85b9d939",
      "userid": "25065109",
      "uuid": "6d63772c-9c41-41e2-9080-49dd833d9cc4",
      "displayName": "Marc"
    }
  },
  "selectedUser": "6d63772c9c4141e2908049dd833d9cc4",
  "launcherVersion": {
    "name": "1.5.2",
    "format": 17
  }
}')
file.close()

The error I get:

    marc@Mezex:~/MineCrack$ ./MineCrack.py
      File "./MineCrack.py", line 9
        file.write('{

I am writing a program that upon startup of minecraft, some files are changed. One file that needs to be changed is "launcher_profiles.json". All I need to do is overwrite the text inside the document with:

{
  "profiles": {
    "MODS 7.10": {
      "name": "Forge",
      "lastVersionId": "mods7.10"
    },
    "Forge": {
      "name": "Forge"
    },
    "mods": {
      "name": "mods",
      "lastVersionId": "mods"
    }
  },
  "selectedProfile": "Forge",
  "clientToken": "e1a07b41-8e41-44b5-9781-3dd3a201bf30",
  "authenticationDatabase": {
    "6d63772c9c4141e2908049dd833d9cc4": {
      "username": "Marc",
      "accessToken": "df914be0efcc4f16aedb532d85b9d939",
      "userid": "25065109",
      "uuid": "6d63772c-9c41-41e2-9080-49dd833d9cc4",
      "displayName": "Marc"
    }
  },
  "selectedUser": "6d63772c9c4141e2908049dd833d9cc4",
  "launcherVersion": {
    "name": "1.5.2",
    "format": 17
  }
}

I need the text to be exactly like that, the spaces, and line changes included.


Solution

  • Your string is a multi-line string. In Python, you use ''' or """ to delimit multiline strings*.

    Change your file.write() to look like this:

    file.write('''{
        blah, blah
        blah
    ''')