2011-11-06 1 views
25

テキストファイルを保存する場所をPythonにどのように伝えますか?WindowsとMacの特定のディレクトリに.txtファイルを保存するPythonを教えてください

たとえば、私のコンピュータはデスクトップからPythonファイルを実行しています。デスクトップ上ではなく、ドキュメントフォルダにすべてのテキストファイルを保存します。このようなスクリプトではどうしたらいいですか?

name_of_file = raw_input("What is the name of the file: ") 
completeName = name_of_file + ".txt" 
#Alter this line in any shape or form it is up to you. 
file1 = open(completeName , "w") 

toFile = raw_input("Write what you want into the field") 

file1.write(toFile) 

file1.close() 

答えて

37

書き込み用にファイルハンドルを開くときに絶対パスを使用してください。

import os.path 

save_path = 'C:/example/' 

name_of_file = raw_input("What is the name of the file: ") 

completeName = os.path.join(save_path, name_of_file+".txt")   

file1 = open(completeName, "w") 

toFile = raw_input("Write what you want into the field") 

file1.write(toFile) 

file1.close() 

自動的にユーザーのドキュメントフォルダのパスを取得するにはブライアンの答えで説明するように、必要に応じてos.path.abspath()と組み合わせることができます。乾杯!

+0

ありがとう – user1031493

16

os.path.joinを使用して、Documentsディレクトリへのパスと、ユーザーが指定したcompleteName(filename?)を組み合わせます。

os.path.join(os.path.expanduser('~'),'Documents',completeName) 

その他はos.path.abspathを使用して提案している:あなたはDocumentsディレクトリがユーザのホームディレクトリからの相対になりたい場合は

import os 
with open(os.path.join('/path/to/Documents',completeName), "w") as file1: 
    toFile = raw_input("Write what you want into the field") 
    file1.write(toFile) 

、あなたのようなものを使用することができます。 os.path.abspathは、'~'をユーザーのホームディレクトリに解決しないことに注意してください。

In [10]: cd /tmp 
/tmp 

In [11]: os.path.abspath("~") 
Out[11]: '/tmp/~' 
関連する問題