Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #80448

Re: Python script that does batch find and replace in txt files

Newsgroups comp.lang.python
Date 2014-11-09 17:49 -0800
References <mailman.15612.1415574059.18130.python-list@python.org>
Message-ID <a8e23ec0-8642-4fa5-b9be-3dc4c214a9a6@googlegroups.com> (permalink)
Subject Re: Python script that does batch find and replace in txt files
From Syed Khalid <khalidness@gmail.com>

Show all headers | View raw


Albert,

Code is not removing  empty lines containing blank characters and not removing leading and trailing spaces present in each line. 




import glob, codecs, re, os

regex = re.compile(r"Age: |Sex: |House No:  ") # etc etc

for txt in glob.glob("D:/Python/source/*.txt"):   
    with codecs.open(txt, encoding="utf-8") as f:
        oldlines = f.readlines()
    for i, line in enumerate(oldlines):
        if "Elector's Name:" in line:
            break
    newlines = [regex.sub("", line).strip().replace("-", "_") for line in oldlines[i:]]
    with codecs.open(txt + "_out.txt", "wb", encoding="utf-8") as w:
        w.write(os.linesep.join(newlines))

Kindly do the needful

Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Re: Python script that does batch find and replace in txt files Albert-Jan Roskam <fomcl@yahoo.com> - 2014-11-09 14:58 -0800
  Re: Python script that does batch find and replace in txt files Syed Khalid <khalidness@gmail.com> - 2014-11-09 17:49 -0800
    Re: Python script that does batch find and replace in txt files alister <alister.nospam.ware@ntlworld.com> - 2014-11-10 11:28 +0000

csiph-web