gpt4 book ai didi

python - 使用 Python 搜索并用双引号替换 csv 中的行

转载 作者:行者123 更新时间:2023-12-01 08:28:01 25 4
gpt4 key购买 nike

我需要处理一些 .csv 文件。其中一些字段条目包含 1 个双引号 ("),或者可能有多个双引号与其他文本混合。我需要将它们全部转义。到目前为止,我正在这样做:

def process_file():
input_path = 'input.txt'
output_path = 'output.txt'
with open(input_path) as input_file, open(output_path, 'w+') as output_file:
for line in input_file:
newline = line.replace('"', '""""')
output_file.write(newline)

如何确保替换仅发生在单个字符上,并且不会替换 """""" 等。

我想使用 python 而不是任何命令行解决方案。另外,这些文件非常大,这就是为什么我循环遍历各行而不是将整个文件加载到内存中。

最佳答案

感谢@mkrieger1和this question ,我能够整理出这个解决方案:

def process_file():
input_path = 'input.txt'
output_path = 'output.txt'
with open(input_path) as input_file, open(output_path, 'w+') as output_file:
for line in input_file:
newline = re.sub(r'(?<!")"(?!")', '""""', line)
output_file.write(newline)

关于python - 使用 Python 搜索并用双引号替换 csv 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com