繁体   English   中英

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将返回 tcl 代码中的f等价物。

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

暂无
暂无

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

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