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

如何解决Python中“not all arguments converted during string formatting”错误?

Fixing "not all arguments converted during string formatting" Error in Your Python Code

Hey there! Let's break down what's causing that error and fix it step by step.

The Root Cause

Your string formatting is in the wrong place. Take a look at this problematic line:

f = textParse(open('email/spam/%d.txt', encoding="UTF-8" % i))

Here, you’re accidentally trying to apply the % i formatting to the "UTF-8" string (which has no placeholder like %d to replace), while the actual filename 'email/spam/%d.txt' still has an unprocessed %d that needs to be swapped with i. This mismatch between expected placeholders and provided arguments triggers the error you’re seeing.

The Fixed Code

First, format the file path correctly, then pass it to open() with the encoding parameter. I also recommend using a with statement to handle file I/O safely—it automatically closes the file when you’re done, preventing resource leaks:

# Format the file path first to replace %d with the value of i
file_path = 'email/spam/%d.txt' % i

# Open the file, read its content, then process with textParse
with open(file_path, encoding="UTF-8") as file:
    file_content = file.read()
    wordList = textParse(file_content)

# Continue with your existing logic
docList.append(wordList)
fullText.extend(wordList)
classList.append(1)

Why This Works

  • We resolve %d in the filename first using % i, so file_path becomes a valid path like 'email/spam/1.txt' (depending on what i is set to).
  • The encoding="UTF-8" parameter is now passed correctly to open() without any unintended formatting.
  • The with statement takes care of closing the file for you, which is a best practice in Python file handling.

If your textParse function is designed to take a file object directly instead of a string, you can adjust it like this:

file_path = 'email/spam/%d.txt' % i
with open(file_path, encoding="UTF-8") as file:
    wordList = textParse(file).read()  # Tweak based on textParse's actual behavior

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:16:09