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

Python实现行长度超3000自动换行及SQL写入代码修改

Modifying the write_sql Function for Automatic Line Wrapping

Got it, let's fix that function to handle those extra-long queries. The goal is to split any query over 3000 characters into shorter lines, while keeping the original behavior of separating each query with a newline. Here's how to do it:

Updated Code

First, here's the modified function that does exactly what you need:

def write_sql(self, queries):
    max_line_length = 3000
    with open(file, 'w') as f:
        for query in queries:
            # Split the query into chunks of 3000 characters max
            wrapped_segments = [query[i:i+max_line_length] for i in range(0, len(query), max_line_length)]
            # Write each chunk as a line, then add a newline to separate from the next query
            f.write('\n'.join(wrapped_segments) + '\n')

How It Works

  • Chunking long queries: The list comprehension [query[i:i+max_line_length] ...] breaks the query into pieces, each no longer than 3000 characters. For queries shorter than 3000 chars, this just creates a single segment—so no unnecessary changes there.
  • Writing to file: We join these chunks with newlines to turn them into separate lines, then add one final newline at the end of each query (just like your original code did) to keep queries separated cleanly.

Bonus: SQL-Friendly Wrapping (Optional)

If you want to avoid splitting in the middle of a word or SQL keyword (to make the wrapped queries more readable), we can tweak the logic to split at the nearest whitespace before the 3000-character mark. Here's a version that does that:

def wrap_query(query, max_len=3000):
    lines = []
    while len(query) > max_len:
        # Find the last space before the 3000-character limit
        split_pos = query.rfind(' ', 0, max_len)
        # If no space exists (super rare in SQL), split exactly at 3000
        if split_pos == -1:
            split_pos = max_len
        lines.append(query[:split_pos])
        # Trim leading space from the next segment to avoid extra spaces
        query = query[split_pos:].lstrip()
    lines.append(query)
    return lines

def write_sql(self, queries):
    with open(file, 'w') as f:
        for query in queries:
            wrapped_lines = wrap_query(query)
            f.write('\n'.join(wrapped_lines) + '\n')

This way, your wrapped lines will end at natural breaks, making the SQL easier to scan if you ever need to read the file manually.

内容的提问来源于stack exchange,提问作者Aaditya R Krishnan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 22:22:43