import sys, re file = open("c:/sample.txt", "r") newfile = open("c:/sample2.txt", "w") contents = file.read() def dashrepl(matchobj): return matchobj.group(1) newfile.write(re.sub("(.*?\.jpe?g).*", dashrepl, contents)) newfile.close(); file.close()