Search code examples
pythonerror-handlingopenfiledialogread-write

copy content of file to another file using python script


i have this python script that open a file dialog and select a text file than copy its content to another file.

when i open the second file it still empty

can anyone help me to solve this problem ?

OPenDirectory.py

#!/usr/bin/python

import Tkinter 
import tkFileDialog

''''Open txt files in the selected path '''
def OpenRead():

    Tkinter.Tk().withdraw()
    in_path = tkFileDialog.askopenfile(initialdir = 'C:\Users\LT GM\Downloads', filetypes=[('text files', ' TXT ')])
    readingFile = in_path.read()
    writeFile = open ('copiedFile.txt', 'w')
    writeFile.write(readingFile)
    print " we'r done!!" 
    in_path.close()
    writeFile.close()


if __name__== "__main__":
    OpenRead()

Solution

  • Line by line way of copying from file to file:

    #!/usr/bin/python
    
    from os import listdir
    from os.path import isfile, join
    
    def readWrite():
        mypath = 'D:\\'
        files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
        for file in files:
            if file.split('.')[1] == 'txt':
                outputFileName = 'out-' + file
                with open(mypath+outputFileName, 'w') as w:
                    with open(mypath+file) as f:
                        for l in f:
                            print l
                            w.write(l)
    
    if __name__== "__main__":
        readWrite()
    

    UPDATE: updated the code above, so it reads all the txt files in a specified directory and copies them into other files. You can play with directories how you like. I also added a "print l" which will print the contents of the incoming file.