0

I am a beginner and I have an issue with a short code. I want to replace a string from a csv to with another string, and put out a new csv with an new name. The strings are separated with commas.

My code is a catastrophe:

import csv

f = open('C:\\User\\Desktop\\Replace_Test\\Testreplace.csv')
csv_f = csv.reader(f)

g = open('C:\\Users\\Desktop\\Replace_Test\\Testreplace.csv')
csv_g = csv.writer(g)


findlist = ['The String, that should replaced']
replacelist = ['The string that should replace the old striong']


#the function  ?:
def findReplace(find,replace):
s = f.read()
for item, replacement in zip(findlist,replacelist):
s = s.replace(item,replacement)
g.write(s)

for row in csv_f:
print(row)

f.close()
g.close()
1
  • 2
    Could you correct the indentation please? Commented Nov 16, 2017 at 17:48

1 Answer 1

4

You can do this with the regex package re. Also, if you use with you don't have to remember to close your files, which helps me.

EDIT: Keep in mind that this matches the exact string, meaning it's also case-sensitive. If you don't want that then you probably need to use an actual regex to find the strings that need replacing. You would do this by replacing find_str in the re.sub() call with r'your_regex_here'.

import re

# open your csv and read as a text string
with open(my_csv_path, 'r') as f:
    my_csv_text = f.read()

find_str = 'The String, that should replaced'
replace_str = 'The string that should replace the old striong'

# substitute
new_csv_str = re.sub(find_str, replace_str, my_csv_text)

# open new file and save
new_csv_path = './my_new_csv.csv' # or whatever path and name you want
with open(new_csv_path, 'w') as f:
    f.write(new_csv_str)
Sign up to request clarification or add additional context in comments.

2 Comments

This requires the CSV file to fit into memory. A more robust solution might be to process one line at a time and write it out to a temporary file, then rename it at the end so it replaces the original if the main program completed successfully.
1. This might lead to false positives if the string is a substring (e.g. ham vs chamber) 2. This could use str.replace as regex functionality is not needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.