Python无法写入循环数据到文件,报错TypeError: write()参数数量错误
Hey there! Let's break down why you're seeing that TypeError and fix the file writing issue so your testing.txt gets populated correctly.
First, the immediate error: TypeError: write() takes exactly one argument (2 given). This comes straight from this line in your code:
outfile.write('results', '/n')
The write() method only accepts a single string argument, but you're passing two here. On top of that, you're writing the literal string 'results' instead of the actual content stored in your results variable, and using /n (forward slash) instead of the proper newline escape sequence \n (backslash).
Here's the corrected code with explanations for each change:
import requests with open('testing.txt', 'w') as outfile: for number in (4,8,5,7,3,10): # Format URL cleanly (note: Google's root + number won't return valid pages, adjust this to your actual target URLs) url = requests.get(f'https://www.google.com/{number}') response = url results = response.content # Print to console for debugging (optional) print(results) # Fix 1: Combine content and newline into one single argument for write() # Fix 2: Decode bytes content to a readable string (response.content returns raw bytes) # Fix 3: Use correct newline sequence '\n' instead of '/n' outfile.write(results.decode('utf-8') + '\n') # Alternative: Use print() to handle newlines automatically (uncomment if preferred) # print(results.decode('utf-8'), file=outfile)
Key Fixes Explained:
- Single argument for
write(): Instead of passing two separate values, combine your content and newline into one string (e.g.,results.decode('utf-8') + '\n'). - Decode bytes to string:
response.contentreturns raw binary data. To write it as a readable text string, use.decode('utf-8')(adjust the encoding if you're fetching content that uses a different charset). - Correct newline sequence: Use
\ninstead of/n—the backslash tells Python this is an escape sequence for a line break. - Optional
print()method: If you prefer,print(results.decode('utf-8'), file=outfile)works becauseprint()automatically adds a newline at the end, and accepts thefileparameter to redirect output to your text file instead of the console.
One quick side note: The URLs you're requesting (https://www.google.com/4, etc.) won't return valid Google pages—Google doesn't structure its URLs this way. Make sure to replace that part with your actual target endpoints if you're testing with real data.
内容的提问来源于stack exchange,提问作者Mia Ella

