i've been trying to create a way to generate config files for a help tool that i've been making. i would like to have the code create a config file in a specific default location that is dependant on the current user on which the code is ran.
this is my basic setup for the code i've been trying to find a way to have username be the variable system_user however when trying this i get a unicode error
import configparser
import os
system_user = os.getlogin()
file_path_input = input('filepath input ')
strength = input('strenght score ')
dexterity = input('dexterity score ')
constitution = input('constitution score ')
intelligence = input('intelligence score ')
wisdom = input('wisdom score ')
charisma = input('charisma score ')
testconfig = configparser.ConfigParser()
testconfig.add_section('stats')
testconfig.set('stats', 'strength', strength)
testconfig.set('stats', 'dexterity', dexterity)
testconfig.set('stats', 'constitution', constitution)
testconfig.set('stats', 'intelligence', intelligence)
testconfig.set('stats', 'wisdom', wisdom)
testconfig.set('stats', 'charisma', charisma)
with open(C:\Users\username\Documents\5e_helper\character cofig, 'w') as configfile:
testconfig.write(configfile)
i've been trying to find a way to have username be the variable system_user however when trying
with open(r'C:\Users\' system_user '\Documents\5e_helper\character cofig', 'w') as configfile:
testconfig.write(configfile)
i get a syntax error SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 1-2: malformed \N character escape
CodePudding user response:
You need to use
with open(r'C:\Users\'' system_user '\Documents\5e_helper\character cofig', 'w') as configfile:
testconfig.write(configfile)
Error is happening because you are using an escape sequence of \'
in 'C:\Users\'
. You can also avoid it using double quotes around path string.
BTW good way to do it is using forward slash (/) instead of back.
CodePudding user response:
Your first string is raw but the second one isn't, which means you need to escape your backslashes since they count as escape characters in normal strings. Or just make the second string raw as well.
with open(r'C:\Users\' system_user r'\Documents\5e_helper\character cofig', 'w') as configfile:
That said, I would just use string format instead of concatenation in order to handle this as single string rather than multiple.
with open(r'C:\Users\{}\Documents\5e_helper\character cofig'.format(system_user), 'w') as configfile: