使用 askopenfilename 打开和读取文件 [英] Opening and reading a file with askopenfilename

查看:31
本文介绍了使用 askopenfilename 打开和读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,我试图让用户打开一个文本文件,一旦用户选择了它,我希望代码能够读取它(这不是一个完整的代码块,只是以显示我所追求的).

I have the following code where I'm trying to allow the user to open a text file and once the user has selected it, I would like the code to read it (this isn't a finished block of code, just to show what I'm after).

但是,我在使用 tkFileDialog.askopenfilename 并添加mode='rb"或使用如下代码并在产生错误的地方使用 read 时遇到了困难.

However, I'm having difficulties either using tkFileDialog.askopenfilename and adding 'mode='rb'' or using the code like below and using read where it produces an error.

有谁知道我可以如何安排这样做,因为我不想为每个项目(例如菜单和列表框)键入 Tkinter.'module'.Tkinter 的初学者,有点困惑!感谢您的帮助!

Does anyone know how I can arrange to do this as I don't wish to have to type Tkinter.'module' for each item such as Menu and Listbox. Beginner to Tkinter and a bit confused! Thanks for the help!

import sys
from Tkinter import *
import tkFileDialog
from tkFileDialog import askopenfilename # Open dialog box

fen1 = Tk()                              # Create window
fen1.title("Optimisation")               #

menu1 = Menu(fen1)

def open():

    filename = askopenfilename(filetypes=[("Text files","*.txt")])
    txt = filename.read()
    print txt
    filename.close()

fen1.mainloop()

显然我在这里得到的错误是:

Obviously the error I'm getting here is:

AttributeError: 'unicode' object has no attribute 'read'

我不明白如何使用 askopen,也无法读取我正在打开的文件.

I don't understand how to use the askopen and also be able to read the file I'm opening.

推荐答案

askopenfilename 只返回一个文件名,你想要的是 askopenfile 接受一个 mode 参数并为您打开文件.

askopenfilename only returns a file name, what you wanted was askopenfile which accepts a mode parameter and opens the file for you.

这篇关于使用 askopenfilename 打开和读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆