【问题标题】:How to replace a special string character pattern using python in csv file如何在csv文件中使用python替换特殊的字符串字符模式
【发布时间】:2022-10-13 02:30:58
【问题描述】:

我是 python 新手,我正在尝试通过用分号“;”替换逗号“,”来编辑 .csv。使用我现在拥有的代码,我可以用除分号以外的任何字符更改逗号。你知道我该怎么做吗?在此先感谢您的帮助。 :)

import re

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

find_str = ","
replace_str = "''"

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

#open new file and save
new_csv_path = r"new_test.csv" # or whatever path and name you want
with open(new_csv_path, 'w') as f:
    f.write(new_csv_str)

【问题讨论】:

  • 尝试将replace_str = 与包含分号字符的撇号字符(而不是双引号)一起使用。
  • 1)@dat,那行不通“replace_str = ;” “replace_str = ;SyntaxError:语法无效”.双引号是要走的路。 2) 对我有用:find_str = "," replace_str = ";" re.sub(find_str, replace_str, 'test, test2') 'test; test2' 3) 您需要提供一些示例数据和您收到的完整错误消息。添加为问题的更新.
  • @AdrianKlaver 我想我本可以更清楚。不是反引号——单引号。 ASCII 39。这应该可以正常工作:replace_str = ';' 在 python 2 或 python 3 下。
  • 就像replace_str = ";"

标签: python csv modifier


【解决方案1】:

该代码适用于;

cat semi_colon_test.csv                                                                                                                                                                                                 
1,2,3,4
5,6,7,8

import re

with open('semi_colon_test.csv') as f:
    file_text = f.read()
    replaced_text = re.sub(find_str, replace_str, file_text)
    with open('replaced_test.csv', 'w') as r_file:
        r_file.write(replaced_text)

cat replaced_test.csv                                                                                                                                                                                                   
1;2;3;4
5;6;7;8



【讨论】:

    猜你喜欢
    • 2018-09-11
    • 1970-01-01
    • 2014-07-22
    • 2022-01-22
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    相关资源
    最近更新 更多