Python:如何将特定于特征的文本添加到文本文件中

时间:2014-08-25 18:40:37

标签: python string file ubuntu editing

我正在使用Python编程语言编写程序。 这是我的python脚本的一部分:

#!/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()

我得到的错误:

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

我正在编写一个程序,在启动我的世界时,一些文件被更改。需要更改的一个文件是" launcher_profiles.json"。我需要做的就是用以下内容覆盖文档中的文本:

{
  "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
  }
}

我需要文本完全相同,包含空格和行更改。

1 个答案:

答案 0 :(得分:5)

您的字符串是一个多行字符串。在Python中,您使用'''"""来分隔多行字符串*

将您的file.write()更改为:

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