Python。文件打开程序

Python. File open procedure

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

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]

要使用文件对话框,您必须导入 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")

更像 pythonic 的方式是使用 with 语句:

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

注意如果你想获取路径的同时打开它可以使用askopenfile而不是askopenfilename。在那种情况下,askopenfile 将 return 相当于 tcl 代码中的 f

os.path 模块为您提供了大量处理文件名的函数。