简体   繁体   中英

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()

ChangedScipt

#!/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':

            if file.strip() in unwanted:
                continue
                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()
blacklist = set(['thumbnails', 'quraan', 'cache'])

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    for line in infile:
        if line.strip() in blacklist: continue  # if you want to match the full line
        # if any(word in line for word in blacklist): continue  # if you want to check if a word exists on a line
        outfile.write(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM