0

I have file named config.py, content like below:

logindata = [
  {'user': '18320967034', 'password': '123456'}
]

I wanna modify the logindata and write it back,

import config
config.logindata[0]['password'] = 'xxxx'

How can I write it back to config.py?

Please don't tell me to use .ini/configparser

Alireza
  • 100,211
  • 27
  • 269
  • 172
TreeCatCat
  • 143
  • 1
  • 1
  • 12
  • 2
    (a) Writing it that way is *not persistent*, and (b) never store passwords unhashed... – Willem Van Onsem Jul 06 '17 at 09:56
  • @WillemVanOnsem if it's the login information for an API used by a web service then you will need to store the password unhashed. – Nick Chapman Jul 06 '17 at 10:01
  • Can you change the way that the config is stored? If you are going to want to change the config it would make more sense to be using `pickle` to save and load your config. – Nick Chapman Jul 06 '17 at 10:02
  • @NickChapman: yeah, but then still it would make sense to encrypt it. – Willem Van Onsem Jul 06 '17 at 10:05
  • @WillemVanOnsem it wouldn't matter. You're going to be storing the encryption key and the decryption procedure on the same machine. By the time that someone has hacked your machine and could just normally read the password they can also read the instructions you've written to decrypt an encrypted password. – Nick Chapman Jul 06 '17 at 10:06
  • But is there any way to write the change back? not picle, not configparser – TreeCatCat Jul 06 '17 at 10:19
  • Do you have any reasonable justification not to use a dedicated data structure like INI, JSON, YAML and such for your config? – zwer Jul 06 '17 at 10:41

2 Answers2

0

If you are absolutely dead set on doing this you will likely need to hack this together. You can do something like the following

import json
import config

with open("config.py", "w") as config:
    config.logindata[0]['password'] = 'xxxx'
    code = "logindata = " + json.dumps(config.logindata)
    config.write(code)

I just want to say that doing this is really hacky and is not a good way to be doing this. But I don't know any other way to do this without using a proper saving and loading protocol.

Nick Chapman
  • 4,402
  • 1
  • 27
  • 41
0

Unless you don't think about your security. Than you can go this way.

import config
config.logindata[0]['password'] = 'xxxx'
#print(config.logindata)
config_string = "".join(('logindata = [',str(config.logindata[0]),"]"))
file = open("config.py", 'w')
file.write(config_string)
file.close()
R.A.Munna
  • 1,699
  • 1
  • 15
  • 29