2016-07-28 115 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是代表一個打開的文件的對象。