用自定义文件路径用configparser创建配置文件



我一直在尝试创建一种方法来生成配置文件的帮助工具,我一直在做。我想有代码创建一个配置文件在一个特定的默认位置,这是依赖于当前用户上的代码运行。

这是我的基本设置的代码,我一直试图找到一种方法,让用户名是变量system_user然而,当尝试这个我得到一个unicode错误

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:UsersusernameDocuments5e_helpercharacter cofig, 'w') as configfile:
testconfig.write(configfile)

我一直试图找到一种方法,有用户名是变量system_user然而,当尝试

with open(r'C:Users' + system_user + 'Documents5e_helpercharacter cofig', 'w') as configfile:
testconfig.write(configfile)

我得到一个语法错误SyntaxError:(unicode错误)'unicodeescape'编解码器无法解码位置1-2的字节:畸形的N字符转义

你需要使用

with open(r'C:Users'' + system_user + 'Documents5e_helpercharacter cofig', 'w') as configfile:
testconfig.write(configfile)

发生错误,因为您在'C:Users'中使用了'的转义序列。你也可以使用双引号来避免它。

顺便说一句,好方法是使用正斜杠(/)代替反斜杠。

您的第一个字符串是原始的,但第二个字符串不是,这意味着您需要转义反斜杠,因为它们在正常字符串中算作转义字符。或者将第二个字符串也设置为raw。

with open(r'C:Users' + system_user + r'Documents5e_helpercharacter cofig', 'w') as configfile:

也就是说,我将使用字符串格式而不是连接,以便将其作为单个字符串而不是多个字符串处理。

with open(r'C:Users{}Documents5e_helpercharacter cofig'.format(system_user), 'w') as configfile: