如何将含引号内换行的API返回字节串转换为规范CSV文件?
解决API返回字节串生成CSV时字段内换行的问题
核心问题是区分CSV行分隔的换行和字段内部的换行——我们需要保留行末尾的换行作为分隔符,把字段内(引号包裹区域)的换行转成字符串转义符\n,避免行被错误拆分。以下是两种可行方案:
方法一:手动处理字段内换行转义
先解码字节串、转义HTML实体,再遍历字符串识别引号边界,替换内部换行:
import html # 模拟API返回的字节串 response_bytes = b'column_title_1, column_title_2, column_title_3\nvalue1_1, value1_2, value1_3\nvalue2_1, value2_2("Perfect!\nThank you"), value2_3\nvalue3_1, value3_2, value3_3' # 1. 解码字节串为字符串,转义HTML实体(把"换成") response_str = html.unescape(response_bytes.decode('utf-8')) # 2. 遍历字符串,替换引号内的实际换行为转义字符\n def fix_quoted_newlines(csv_content): in_quote = False result = [] for char in csv_content: if char == '"': in_quote = not in_quote # 仅在引号内时,把换行替换成转义的\n if char == '\n' and in_quote: result.append('\\n') else: result.append(char) return ''.join(result) fixed_csv = fix_quoted_newlines(response_str) # 3. 写入CSV文件 with open('output.csv', 'w', encoding='utf-8') as f: f.write(fixed_csv)
方法二:用CSV模块规范处理
如果需要更健壮的解析(比如处理复杂字段格式),用Python内置csv模块自动识别引号边界,再按需替换换行:
import csv from io import StringIO import html response_bytes = b'column_title_1, column_title_2, column_title_3\nvalue1_1, value1_2, value1_3\nvalue2_1, value2_2("Perfect!\nThank you"), value2_3\nvalue3_1, value3_2, value3_3' response_str = html.unescape(response_bytes.decode('utf-8')) # 1. 读取CSV内容,自动识别引号内的换行 csv_reader = csv.reader(StringIO(response_str), quotechar='"', skipinitialspace=True) # 2. 写入时替换字段内的换行为转义符,或直接保留(标准CSV会自动用引号包裹含换行的字段) with open('output_standard.csv', 'w', newline='', encoding='utf-8') as out_file: csv_writer = csv.writer(out_file, quotechar='"', quoting=csv.QUOTE_NONNUMERIC) for row in csv_reader: # 可选:把字段内的实际换行替换成转义的\n cleaned_row = [field.replace('\n', '\\n') if field else field for field in row] csv_writer.writerow(cleaned_row)
内容的提问来源于stack exchange,提问作者ALL
相关产品推荐
相关产品推荐

