Skip to content
Advertisement

Opening and reading a file with 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).

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.

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'

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement