Arthur Aguirre
Arthur Aguirre

Reputation: 103

Python search and replace in CSV iteratively by line

I'm looking to extend the Python solution found here: PowerShell is slow (much slower than Python) in large Search/Replace operation?

To replace string across CSV files I use: findReplace("c:/temp/csv", "Search String", "Replace String", "*.csv")

What I'd like to be able to do is have "Search" and "Replace" be a list of terms. I cannot use re as the term is unknown prior to finding it manually. However, since the CSV files have the same structure and may have the same string values finding the term once is sufficient to automate the process.

Any insight on best approach would be greatly appreciated.

Upvotes: 0

Views: 1150

Answers (1)

thefourtheye
thefourtheye

Reputation: 607

You mentioned lists, so I'm guessing you have two lists like this:

findlist = ['hey', 'hello', 'hi']
replacelist = ['bye', 'see ya', 'brb']

You can load them into a dictionary with this:

rep = dict(zip(findlist, replacelist))

Then the function can be written:

for item in findlist:
    findReplace("c:/temp/csv", item, rep[item], "*.csv")

I'm definitely a StackOverflow newbie, but it would help if you provided sample inputs and the desired outputs. Otherwise we'll just guess, and the answer may not be what you want.

Upvotes: 1

Related Questions