Opening and reading a file called askopenfilename

I have the following code where I try to allow the user to open a text file, and as soon as the user selects it, I would like the code to read it (this is not a ready-made block of code, just to show what I need).

However, I am having difficulty either using tkFileDialog.askopenfilename, either adding 'mode =' rb '' or using the code as shown below, and using reading, where it creates an error.

Does anyone know how I can do this since I do not want to enter Tkinter.'module for every item, such as a menu and list. Beginner from Tkinter and a little embarrassed! 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 am getting here is:

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

I do not understand how to use askopen, as well as being able to read the file that I open.

+8
python tkinter
source share
3 answers

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

+6
source share

filename in your code example is just a string indicating the name of the file you want to open. You need to pass this to the open() method to return a file descriptor for the name. Then you can read from the file descriptor.

Here's the quick and dirty code that runs directly in the Python interpreter. (You can run this in a script, but I really like the REPL interfaces to quickly try and do something. You may also like it.)

 $ python Python 2.7.3 (default, Apr 20 2012, 22:39:59) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter >>> from tkFileDialog import askopenfilename >>> root = Tkinter.Tk() ; root.withdraw() '' >>> filename = askopenfilename(parent=root) >>> filename '/tmp/null.c' >>> f=open(filename) >>> f.read() '#include<stdio.h>\n\nint main()\n{\n for(;NULL;)\n printf("STACK");\n\n return 0;\n}\n\n' >>> f.close() >>> 

Note that there is nothing specific to Tkinter in reading the file - the dialog box just gives you the file name.

+7
source share

Your error is the name of your function. I just changed def open() to def open1() and it works.

 def open1(): filename = askopenfilename(parent=fen1) print(filename) f = open(filename) txt = f.read() print txt f.close() 
0
source share

All Articles