繁体   English   中英

使用带有自定义文件路径的 configparser 创建配置文件

[英]creating a config file with configparser with a custom file path

我一直在尝试创建一种方法来为我一直在制作的帮助工具生成配置文件。 我想让代码在特定的默认位置创建一个配置文件,该位置取决于运行代码的当前用户。

这是我的代码的基本设置 我一直在尝试找到一种方法让用户名成为变量 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:\Users\username\Documents\5e_helper\character cofig, 'w') as configfile:
    testconfig.write(configfile)

我一直在尝试找到一种方法让用户名成为变量 system_user 但是在尝试时

with open(r'C:\Users\' + system_user + '\Documents\5e_helper\character cofig', 'w') as configfile:
    testconfig.write(configfile)

我收到语法错误 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 1-2: malformed \N character escape

你需要使用

with open(r'C:\Users\'' + system_user + '\Documents\5e_helper\character cofig', 'w') as configfile:
    testconfig.write(configfile)

发生错误是因为您在'C:\Users\'中使用了\'的转义序列。 您也可以在路径字符串周围使用双引号来避免它。

顺便说一句,这样做的好方法是使用正斜杠 (/) 而不是反斜杠。

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

with open(r'C:\Users\' + system_user + r'\Documents\5e_helper\character cofig', 'w') as configfile:

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

with open(r'C:\Users\{}\Documents\5e_helper\character cofig'.format(system_user), 'w') as configfile:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM