python文件打开过程

python文件打开过程,python,tcl,Python,Tcl,以下代码(用TCL编写)如何在Python 2.7中翻译 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

以下代码(用TCL编写)如何在Python 2.7中翻译

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]

要使用“文件”对话框,必须导入。它可以这样使用:

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")
使用
with
语句将是一种更具python风格的方式:

with open(file, "r") as f:
    <code to work with the file here>
打开(文件“r”)作为f:
<此处使用文件的代码>
请注意,如果要获取路径并同时打开它,可以使用
askopenfile
而不是
askopenfilename
。在这种情况下,
askopenfile
将返回tcl代码中与
f
等效的值


该模块为您提供了大量处理文件名的函数

我添加了
tcl
标记,因为至少你会想要一个懂两种语言的人的答案。然而,你应该先尝试自己翻译,并询问你遇到困难的具体问题。如果您不懂Python,那么教程将是一个很好的起点。感谢您的指导。我将试着问一些具体的问题。您是否关心
完整路径
值,或者这只是达到目的的一种手段?(阅读:您可以在python中获取文件名,而无需首先获取根名称)主要问题是如何打开一个包含当前目录文件列表的窗口。您做过任何研究吗?一个简单的谷歌搜索“tkinter文件对话框”会得到很多结果。非常感谢你的帮助!