2016-03-07 216 views
-2

以下代碼(用TCL編寫)如何在Python 2.7中轉換?Python。文件打開程序

set types {{"Text file" ".txt"} {"All Files" "*.*"}} 
set file [tk_getOpenFile -filetypes $types -parent . -initialdir [pwd]] 
if {$file=={}} {return} 
set f [open $file r] 
set fullPath [file rootname $file] 
set name [lrange [split $fullPath "/"] end end] 
+0

我添加了'tcl'標籤,因爲至少你會想要一個知道兩種語言的人的回答。但是,您應該先嚐試自己翻譯,然後詢問您遇到的具體問題。如果你不瞭解Python,教程將是一個很好的起點。 – chepner

+0

感謝您的理事會。我會試着問一些具體的問題。 –

+0

你關心'fullPath'的價值,還是隻是達到目的的一種手段? (閱讀:你可以在沒有獲取根名稱的情況下在python中獲得文件名) –

回答

1

要使用文件對話框,您必須導入tkFileDialog。它可以這樣使用:

import tkFileDialog 
import os    # so we can call getcwd() 
... 
types = (("Text file", ".txt"), ("All Files", "*.*")) 
file = tkFileDialog.askopenfilename(filetypes=types, initialdir=os.getcwd()) 

要打開文件,有很多方法。逐字翻譯應該是:

f = open(file, "r") 

更Python的方式將與with聲明:

with open(file, "r") as f: 
    <code to work with the file here> 

請注意,如果你想獲得的路徑,並在同一時間,你可以用打開askopenfile而不是askopenfilename。在這種情況下,askopenfile將在tcl代碼中返回相當於f的值。

os.path模塊爲您提供了大量使用文件名的函數。

+0

非常感謝您的幫助! –