Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over files and replace text

I'm python beginner: how can I iterate over csv files in one directory and replace strings e.g.

ww into vv
.. into --

So, I do not want to replace lines having ww into vv, just those string on this line. I tried something like

#!/Python26/
# -*- coding: utf-8 -*-

import os, sys
for f in os.listdir(path):
    lines = f.readlines() 

But how to proceed?

like image 246
atricapilla Avatar asked Jan 21 '23 13:01

atricapilla


1 Answers

import os
import csv

for filename in os.listdir(path):
    with open(os.path.join(path, filename), 'r') as f:
        for row in csv.reader(f):
            cells = [ cell.replace('www', 'vvv').replace('..', '--')
                      for cell in row ]
            # now you have a list of cells within one row
            # with all strings modified.

Edit: Is it for you to learn/practice Python or you just need to get the job done? In the latter case, use the sed program:

sed -i 's/www/vvv/g' yourPath/*csv
sed -i 's/\.\./,,/g' yourPath/*csv
like image 123
eumiro Avatar answered Jan 31 '23 08:01

eumiro