[Tutor] Using Python and Regex
Alex Kleider
akleider at sonic.net
Sun Aug 10 18:05:10 CEST 2014
On 2014-08-10 04:30, Bill wrote:
> Hi,
>
> I'm relatively new to Python and I'm trying to write a script to
> iterate through a series of text files in folder searching for some
> specific text and write it to a CSV.
>
> I plan to use Regex to match the text and I have already identified
> the Regex to do this. I've also got as far as creating a CSV using
> python but, being new to this, I'm looking for some pointers on how to
> traverse through the folder and open each file in turn to check the
> content for matches using Regex.
>
> Any advice would be gratefully received.
>
> Regards
>
> Bill
I suggest you begin with os.path.walk()
https://docs.python.org/2/library/os.path.html
To traverse files line by line:
for f_name in mylistoffiles:
try:
f = open(f_name, 'r', encoding='utf-8')
except IOError as err_report:
# you might want to keep track of failures
continue
for line in f:
# apply your regex code and do whatever
More information about the Tutor
mailing list