mercredi 23 décembre 2015

how to copy content of file to another file with deleting some lines in a TXT file based on some strings with python

i have this python script that open a file dialog and select a text file than copy its content to another file, what i need to do before i copy to the next file is to delete several lines based on some strings that are predefined in the script.

the problem is that the file is copied as it is without deleting anything.

can anyone help me to solve this issue??

OPenDirectory.py

 #!/usr/bin/python

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


def readWrite():
    unwanted = set(['thumbnails', 'tikare', 'cache'])
    mypath = "C:\Users\LT GM\Desktop/"

    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 l != unwanted:
                            print l
                            w.write(l)
    in_path.close()
if __name__== "__main__":
    readWrite()

Aucun commentaire:

Enregistrer un commentaire