簡體   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