Gems of Python
Requirement – Find out immediately if the files are different and then point out the differences.
Solution – use – filecmp.cmp and then difflib.ndiff. This is great for small size file.
a. filecmp.cmp(file1,file2,shallow=False))
b.
x = file1.readlines(); file1.close()
z = file2.readlines(); file2.close()
for line in difflib.ndiff(x,z):
if line.startswith(“+”) or line.startswith(“-”):
print(line)
2. Returning of multiple pieces of information.
Solution – use the return intuitively.
return 1, numfiles, thequeue # just magic.
so at other side
status, numfilesprocessed,listprocessedfiles = funcname(params)
does the work.
3. Requirement : Working over two ordered lists
Solution – Use Zip.
for r, s in zip (vernaqueue,engqueue):
if False == (filecmp.cmp(r,s,shallow=False)):
fcompare(r, s,exfile)
4. Requirement – get list of lowercased complete filenames of particular kind in a simple way
Solution : Sheer magic of list comprehension then move on to generators
extlist = [".mdb"]
location = “some directory”
filelist = (os.path.normcase(f) for f in os.listdir(location)) # map functionality
filelist = (os.path.join(location,f) for f in filelist if os.path.splitext(f)[1] in extlist)