abc.txt
次のような構成ファイルがあります。
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"
abc.txt
ハードコーディングを避けるために、これらのパスを から読み取り、プログラムで使用したいと考えています。
abc.txt
次のような構成ファイルがあります。
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"
abc.txt
ハードコーディングを避けるために、これらのパスを から読み取り、プログラムで使用したいと考えています。
ファイルに次のセクションが必要です。
[My Section]
path1 = D:\test1\first
path2 = D:\test2\second
path3 = D:\test2\third
次に、プロパティを読み取ります。
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open(r'abc.txt'))
path1 = config.get('My Section', 'path1')
path2 = config.get('My Section', 'path2')
path3 = config.get('My Section', 'path3')
**your_config_name.yml**
あなたの場合の便利な解決策は、次のような名前の yaml ファイルに構成を含めることです
。
path1: "D:\test1\first"
path2: "D:\test2\second"
path3: "D:\test2\third"
Python コードでは、次のようにして構成パラメーターをディクショナリにロードできます。
import yaml
with open('your_config_name.yml') as stream:
config = yaml.safe_load(stream)
次に、辞書configから次のように path1 にアクセスします。
config['path1']
yaml をインポートするには、最初にパッケージをそのままインストールする必要があります:pip install pyyaml
選択した仮想環境に。
設定ファイルは通常のテキスト ファイルなので、次のopen
関数を使用して読み取るだけです。
file = open("abc.txt", 'r')
content = file.read()
paths = content.split("\n") #split it into lines
for path in paths:
print path.split(" = ")[1]
これにより、パスが出力されます。辞書やリストを使用して保存することもできます。
path_list = []
path_dict = {}
for path in paths:
p = path.split(" = ")
path_list.append(p)[1]
path_dict[p[0]] = p[1]
ファイルの読み取り/書き込みの詳細については、こちらを参照してください。お役に立てれば!