如何解决Python中“not all arguments converted during string formatting”错误?
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
%din the filename first using% i, sofile_pathbecomes a valid path like'email/spam/1.txt'(depending on whatiis set to). - The
encoding="UTF-8"parameter is now passed correctly toopen()without any unintended formatting. - The
withstatement 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

