[Tutor] A question on tkFileDialog's askopenfilename

Robin Munn rmunn@pobox.com
Wed, 29 Aug 2001 10:13:37 -0500


On Wed, Aug 29, 2001 at 11:10:17PM +0900, HY wrote:
> Hi there,
> 
> I want to use tkFileDialog's askopenfilename to let user to choose a file. I
> want to print the file path,and then I want to open file.
> Say, the file a user wants to open is c:\py\something.txt
> I know:
> #------------------------------------
> from tkFileDialog import askopenfilename
> filePath=askopenfilename()
> print "This is the file you chose",filePath
> #------------------------------------
> 
> BUT how can use filePath to open the actual file?

Simply use Python's built-in open() function:

###
from tkFileDialog import askopenfilename
filePath=askopenfilename()
print "This is the file you chose",filePath
file = open(filePath, "rb")
###

The second parameter is "rb" for reading or "wb" for writing. The "b"
means to open the file in binary mode (as opposed to text mode): text
mode will convert CR/LF combinations to single LF's automatically. This
is handy if the file you're wanting to open is actually text, but it
will corrupt non-text files (such as .jpg or .doc files, for instance).
If you *really* want to use text mode, do:

###
file = open(filePath, "r")
###

But on Windows, you should always use binary mode unless you have a
specific reason not to.


> 
> Also I found out that:
> On Windows OS, askopenfilename() returns
> c:/py/something.txt    instead of
> c:\py\something.txt
> (The \ become /)
> Why?

The / character is the standard path-separator on Unix, and most
programming languages are therefore designed to recognize / as the path
separator and use it by default. You can call the os.path.normpath()
function to change / to \ if you want:

###
from tkFileDialog import askopenfilename
import os
filePath = askopenfilename()
filePath = os.path.normpath(filePath)
print "This is the file you chose",filePath
file = open(filePath, "rb")
###

Hope this helps.

-- 
Robin Munn
rmunn@pobox.com