简体   繁体   English

Python。 文件打开程序

[英]Python. File open procedure

How could the following code (written in TCL) be translated in Python 2.7?如何在 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]

To use the file dialog you must import tkFileDialog .要使用文件对话框,您必须导入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:一种更 Pythonic 的方式是使用with语句:

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 .请注意,如果您想获取路径并同时打开它,您可以使用askopenfile而不是askopenfilename In that case, askopenfile will return the equivalent of f in the tcl code.在这种情况下, askopenfile将返回 tcl 代码中的f等价物。

The os.path module gives you plenty of functions for working with filenames. os.path模块为您提供了大量处理文件名的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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