我是一个初学者,我有一个短代码的问题。我想用另一个字符串替换csv中的一个字符串,并生成一个新的 新名称的csv。字符串用逗号隔开。在
我的代码是一场灾难:
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()
您可以使用regex包
re
来完成此操作。另外,如果您使用with
,则不必记住关闭文件,这对我有帮助。在编辑:请记住,这与字符串完全匹配,这意味着它也区分大小写。如果您不希望这样做,那么您可能需要使用实际的正则表达式来查找需要替换的字符串。您可以通过将
re.sub()
调用中的find_str
替换为r'your_regex_here'
。在相关问题 更多 >
编程相关推荐