Python:替换CSV文件中的字符串

2024-10-01 22:35:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个初学者,我有一个短代码的问题。我想用另一个字符串替换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()

Tags: csvthe字符串代码testthatopenreplace
1条回答
网友
1楼 · 发布于 2024-10-01 22:35:01

您可以使用regex包re来完成此操作。另外,如果您使用with,则不必记住关闭文件,这对我有帮助。在

编辑:请记住,这与字符串完全匹配,这意味着它也区分大小写。如果您不希望这样做,那么您可能需要使用实际的正则表达式来查找需要替换的字符串。您可以通过将re.sub()调用中的find_str替换为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)

相关问题 更多 >

    热门问题