簡體   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