无法将python数据打印到outfile

时间:2018-04-15 13:24:01

标签: python python-3.x

我正在尝试将循环数据写入'testing.txt'文件,每个结果都在新行上,但该文件不会生成任何内容。我得到了

  

错误:TypeError:write()只接受一个参数(给定2个)

import requests

with open('testing.txt', 'w') as outfile:
    for number in (4,8,5,7,3,10):
        url = requests.get('https://www.google.com/' + str(number))

        response =(url)
        results = response.content
        print(results)
        outfile.write('results', '/n')
        print (results, file=outfile)

1 个答案:

答案 0 :(得分:-1)

response.text代替response.content正在为我工​​作。

import requests

def request_number(number):
    response = requests.get('https://www.google.com/' + str(number))
    return response.text

with open('testing.txt', 'w') as outfile:
    results = list(map(request_number, (4,8,5,7,3,10)))
    outfile.write("\n".join(results))

编辑:更接近OP代码的另一个版本(根据评论中的要求),也适用于我:

import requests

with open('testing.txt', 'w') as outfile:
    results = []
    for number in (4,8,5,7,3,10):
        url = requests.get('https://www.google.com/' + str(number))

        response =(url)
        results.append(response.text)
        print(results)

    outfile.write("\n".join(results))