You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决CSV写入时字符串被逐字符拆分的问题

Fixing Character Split Problem When Writing to CSV in Python

Hey there, the issue you're facing happens because of how csv.writer.writerow() works—it expects a sequence (like a list or tuple) where each element represents a column in the row. When you pass a plain string (like 'name' or your shop names), Python treats the string as an iterable of individual characters, so each character gets written as a separate column.

Here's how to fix it:

Step 1: Wrap your header and row values in lists

Instead of passing raw strings to writerow(), put them inside a single-element list. This tells the CSV writer to treat the entire string as one column.

Updated CSV Writing Code

with open('coffee_shops.csv', 'w+') as file:
    writer = csv.writer(file)
    # Wrap 'name' in a list to keep it as a single header column
    writer.writerow(['name'])
    for item in bus:
        # Wrap each shop name in a list to prevent character splitting
        writer.writerow([item])

Full Cleaned-Up Working Code

I also removed the unused final list to simplify the code:

import requests
import sys
import csv

url = 'https://api.yelp.com/v3/businesses/search'
api_key = '**censored**'
headers = {'Authorization': 'Bearer ' + api_key}
params = {'term': 'coffee', "location": sys.argv[1]}

response = requests.get(url, headers=headers, params=params)
businesses = response.json()['businesses']

# Use a list comprehension to collect shop names more concisely
bus = [business['name'] for business in businesses]

print('The top 10 coffee shops are: ')
for item in bus[:10]:
    print(item)

# Fixed CSV writing (added newline='' to avoid extra blank rows on Windows)
with open('coffee_shops.csv', 'w+', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['name'])
    for item in bus:
        writer.writerow([item])

Corrected CSV Output Preview

name
Jay Jean Cafe
Legends Caf�
Costa Coffee
The Fig Leaf
Orli Espesso Bar Bakery
...

That should completely eliminate the character splitting issue!

内容的提问来源于stack exchange,提问作者Amen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:02:45