简体   繁体   中英

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.

askopenfilename仅返回文件名,您想要的是askopenfile ,它接受mode参数并为您打开文件。

The filename in your sample code is just that -- a string indicating the name of the file you wish to open. You need to pass that to the open() method to return a file handle for the name. You can then read from the file handle.

Here's some quick and dirty code to run in the Python interpreter directly. (You can run this in a script, too, but I really like REPL interfaces for quickly trying things out. You may like it as well.)

$ 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 especially that there's nothing Tkinter-specific in reading the file -- the dialog box just gives you a filename.

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

def open1():

    filename = askopenfilename(parent=fen1)
    print(filename)
    f = open(filename)
    txt = f.read()
    print txt
    f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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