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

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.content returns 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 \n instead 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 because print() automatically adds a newline at the end, and accepts the file parameter 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:56:31