Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to delete a line in file1 that appeared once or multiple times in file2 in python?
    primarykey
    data
    text
    <p>I have two text files: file1 has 40 lines and file2 has 1.3 million lines I would like to compare every line in file1 with file2. If a line in file1 appeared once or multiple times in file2, this line(lines) should be deleted from file2 and remaining lines of file2 return to a third file3. I could painfully delete one line in file1 from file2 by manually copying the line, indicated as "unwanted_line" in my code. Does anyone knows how to do this in python. Thanks in advance for your assistance. Here's my code:</p> <pre><code> fname = open(raw_input('Enter input filename: ')) #file2 outfile = open('Value.txt','w') unwanted_line = "222" #This is in file1 for line in fname.readlines(): if not unwanted_line in line: # now remove unwanted_line from fname data =line.strip("unwanted_line") # write it to the output file outfile.write(data) print 'results written to:\n', os.getcwd()+'\Value.txt' </code></pre> <p>NOTE:</p> <p>This is how I got it to work for me. I would like to thank everyone who contributed towards the solution. I took your ideas here.I used set(),where intersection (common lines) of file1 with file2 is removed, then, the unique lines in file2 are return to file3. It might not be most elegant way of doing it, but it works for me. I respect everyone of your ideas, there are great and wonderful, it makes me feel python is the only programming language in the whole world. Thanks guys.</p> <pre><code> def diff_lines(filenameA,filenameB): fnameA = set(filenameA) fnameB = set(filenameB) data = [] #identify lines not common to both files #diff_line = fnameB ^ fnameA diff_line = fnameA.symmetric_difference(fnameB) data = list(diff_line) data.sort() return data </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload