FW: [Tutor] deleting CR within files

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Apr 16 17:21:24 EDT 2004


> from Tkinter import *
> import tkFileDialog
> import sys
> def dialog(fileName):
>     top = Tk()
>     top.withdraw()

I'm not sure what this does, I don't think you need it.
But I may be wrong, it certainly should do any harm...

>     initDir = 'C:/windows/desktop'
>     filetype = [('All files', '.*')]
>     fileName = tkFileDialog.askopenfilename(initialdir=initDir,
>                                             filetypes=filetype)
>     return fileName

OK, as suspected you return the filename but the code in
the main program doesn't pick it up.

> And here is the crgui.py module:
>
> import os
> import Tkinter
> import sys
> import dialog
>
> root=Tkinter.Tk()
> f=Tkinter.Button(root, text="Find Files", command=dialog.dialog)
f.pack()
> x=Tkinter.Button(root, text="Close", command=sys.exit)
x.pack()
>
> if f:
>     in_file = open(fileName,'r').readlines()
>     out_file = open(fileName + '_cleaned', 'w')
>     for i in dialog().readline:

dialog is a module not a function. you need to call dialog.dialog()
And even then it returns a finlename not a file so you can't call
readlines. In fact given you have already opened a file for reading
I'm not sure why you are doing this at all?

Assuming you want to ignore your opriginal in_file
You need something like:

      infile = file(dialog.dialog())
      for line in infile:   # in v2.3 readlines is no longer needed
         out_file.write(line[:-1] + '\n')


Which strips the last character from every line and replaces it
with a newline character. You could do pretty much the same with
the strip method:
         out_file.write(line.strip() + '\n')

>     print 'File cleaned'
>     out_file.close()
>     print filename
>
> root.mainloop()
>
> The dialog function is not returning the information I believe.  I
think
> this is where my problem lies.

dialog() probably is returning the filename but a filename is not a
file.
Unfortunately you were calling the module not the function.
BTW Why do you create the Tkinter buttons? You never use them...

I suspect what you really want to do is create a local function
with the stuff inside the if block. Then pass that to the button.
Then when somebody clicks the button your function gets called
and you pop up the dialog, read the filename and process the file.

Like this(warning untested code!):


def cleanFile():
   filename = dialog.dialog()
   if filename:
     try:
       inFile = file(filename)
       outFile = file(filename+'_cleaned','w')
       for line in inFile:
          out_file.write(line.strip() + '\n')
       inFile.close()
       outFile.close()
     except IOError:
       print "Couldn't open file"   # could use warning dialog...

Tkinter.Button(..... command=cleanFile)

I think thats what you are trying to do?

Alan G.




More information about the Tutor mailing list