2017-01-13 7 views
1

暗号化されたパスワードをファイルに保存するプログラムをコーディングしようとしていますが、プログラムの最初の使用時にディレクトリを入力するオプションが必要ですパスワードを保存する場所を知っています。誰も私はそれを達成する方法を知っていますか?初めてプログラムを開くときにのみディレクトリを保存する方法

例、初めて開くプログラム:

dir = input("What directory would you like to use to save your passwords?") 
file_name = dir+"\\passwords.txt" 
open(file_name, "w") # creates the file 
# runs the rest of the program or exits 

はその後、最初の後のプログラムの実行ごとに、それだけでこの部分をスキップします。

答えて

4

パスワードファイルの場所をどこかに保存する必要があります。ユーザーのホームディレクトリに構成ファイルを作成しようとする可能性があります。

from os.path import expanduser, join, exists 
home = expanduser("~") 

if not exists(join(home, '.my-config')): 
    # ask for password file path 
    ... 
    # persist path 
    with open(join(home, '.my-config', 'w')) as config_file: 
      config_file.write(password_file_path) 
else: 
    # read the password file path from the config 
    with open(join(home, '.my-config', 'r')) as config_file: 
      password_file_path=config_file.read() 

# continue with code 
... 

設定ファイルをより使いやすくするには、たとえば、あなたが必要とするすべてのデータを辞書を作成し、設定ファイルにJSON文字列を保存することができます:アプリが起動し、次の操作を行い

その辞書を後でアプリケーションに読み込むことができます。

+1

'open(join(home、 '.my-config'、...'?)を使用する 'join()'の終了用の括弧はありませんか? – Thelmund

+0

ヒントのおかげで、コード –

+0

を編集しました。これは私にとっては理解しがたいものでしたが、いくつかの変更があってもうまくいきました。ありがとう! – Setti7

関連する問題