简体   繁体   中英

Python. File open procedure

How could the following code (written in TCL) be translated in 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]

To use the file dialog you must import tkFileDialog . It can be used like this:

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

To open the file, there are many ways. A literal translation would be:

f = open(file, "r")

A more pythonic way would be with the with statement:

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

Note that if you want to get the path and open it at the same time you can use askopenfile rather than askopenfilename . In that case, askopenfile will return the equivalent of f in the tcl code.

The os.path module gives you plenty of functions for working with filenames.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM