简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM