2016-07-28 12 views
0

指定した(テキスト)ファイルからデータを開いて実行できるようにファイルパスを取得するのに問題があります。以下は、私がこれまでに書いたコードは次のとおりです。Pythonでのファイルパスの取得2.7

def pickfile(): 
    options={} 
    options['defaultextension'] = '.txt' 
    options['filetypes'] = [('all files','.*'), ('text files', '.*txt')] 
    options['initialfile'] = 'sample.txt' 
    options['initialdir'] = 'C:\Users\profcs\Desktop' 

    filename=open(tkFileDialog.askopenfilename(**options)) 
    if filename: 
     print(filename) 
     return 
    with open(filename, 'rb') as f: 
     reader = csv.reader(f) 
     try: 
      for row in reader: 
       print row 
     except csv.Error as e: 
      sys.exit('file %s, line %d: %s' % (filename, reader.line_num,e)) 

but1 = Button(widget1, text='Pick Your File', command=pickfile) 
but1.pack(side=BOTTOM, padx=10, pady=1, anchor=SE) 
but1.config(relief=RAISED, bd=2) 

私は、ファイル名を表示すると、私は今、このフォームでパスを取得:

================ RESTART: C:\Users\profcs\Desktop\BD TEST.py ================ 
<open file u'C:/Users/profcs/Desktop/sample.txt', mode 'r' at 0x01EFF128> 

どのように私はこのパスをフィルタリングすることができますし、だけなので'C:/Users/profcs/Desktop/sample.txt'を取得しますファイルを開くことができますか?

ありがとうございます。

答えて

0

filename.nameは、filenameオブジェクトからのパスを提供します。

私はこのことができます願っています:あなたのケースでは

filename = open(tkFileDialog.askopenfilename(**options)) 
print (filename.name) 
'C:/Users/profcs/Desktop/sample.txt' 

filenameが開かれているファイルを表すオブジェクトです。

関連する問題