Search code examples
pythonfileuser-inputread-write

how to make the user choose the path of the output file using python


I have a python script that reads a file and copies its content to another file while deleting unwanted lines before sending.

The problem is that I want to allow the user to choose the source file and the destination path.

How can this be solved ?

outputSortedFiles.py

#!/usr/bin/python

'''FUNCTION THAT READ SELECTE DFILE AND WRITE ITS 
   CONTENT TO SECOND FILE WITH DELETING
   TH EUNWANTED WORDS'''

import Tkinter
from os import listdir
from os.path import isfile
from os.path import join
import tkFileDialog
import os

def readWrite():
    unwanted = ['thumbnails', 'tyroi', 'cache', 'Total files', 'zeryit', 'Ringtones', 'iconRecv',
                'tubemate', 'ueventd', 'fstab', 'default', 'lpm']
    mypath = r"C:\Users\hHJE\Desktop/filesys" 
    Tkinter.Tk().withdraw()
    in_path = tkFileDialog.askopenfile(initialdir = mypath, filetypes=[('text files', ' TXT ')])    
    files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
    for file in files:
        if file.split('.')[1] == 'txt':
            outputFileName = 'Sorted-' + file
            with open(mypath + outputFileName, 'w') as w:
                with open(mypath + '/' + file) as f:
                    for l in f:
                        if not True in [item in l for item in unwanted]:
                            w.write(l)
                            print ("
                                    *********************************\
                                        THE OUTPUT FILE IS READY\
                                    *********************************\
                                   ")
    in_path.close()
    if __name__== "__main__":
        readWrite()

Solution

  • You can use TkFileDialog just as you did to ask inputFiles :

    outputpath = tkFileDialog.asksaveasfile()
    

    See examples in those tutorials : http://www.tkdocs.com/tutorial/windows.html