[Tutor] Compare two text files

Steven D'Aprano steve at pearwood.info
Mon Oct 13 11:32:16 CEST 2014


On Mon, Oct 13, 2014 at 03:54:59PM +0800, Crusier wrote:
> Hi Alan,
> 
> Attached are the two text files (stocklist.txt & stocklist1.txt) which I
> want to do a comparison with the content of the file, Basically, I want to
> see if there are any new numbers added to the file.
> 
> Please comment on the sequence of the file:
> 1. First, Open up the File No. 1 and put the string into a list.
> 2. Second, Open the File No. 2 and put the string into a list.
> 3. Use difflib to compare

Sounds like a good plan to me. Something like this would work:

py> import difflib
py> a = '1728.HK 1033.HK 2393.HK 0968.HK 3378.HK'.split()
py> b = '1728.HK 1036.HK 2393.HK 0968.HK 2784.HK 3378.HK'.split()
py> print '\n'.join(difflib.unified_diff(a, b))
---

+++

@@ -1,5 +1,6 @@

 1728.HK
-1033.HK
+1036.HK
 2393.HK
 0968.HK
+2784.HK
 3378.HK


Obviously you don't type in the strings '1728.HK...', you read them from 
the files you wish to compare.



-- 
Steven


More information about the Tutor mailing list