简体   繁体   中英

Writing output to a new file in it's own direction with python

I'm struggling with writing the output of the loop to new file. I want to name the new file the name of the variable +.txt. But I'm getting errors on the print part of the code.

import csv
import requests

with open('test.csv', 'r') as file:
    next(file) # drop header
    varlist = [row[0] for row in csv.reader(file, delimiter=",")]

for var in varlist:
    payload = {'api_key': 'API_key', 'query':str(var), 'results':'10', 'country':'gb', 'page':'0'}
    resp = requests.get('https://api.example.com/google', params=payload)
    print(resp.text, file=(str(var) + '.txt'))

How to handle this correctly?

Solved with the problem with putting file key in a better stream object and use 'w'

for var in varlist:
    payload = {'api_key': 'API_key', 'query':str(var), 'results':'10', 'country':'gb', 'page':'0'}
    resp = requests.get('https://api.example.com/google', params=payload)
    print(resp.text, file=open((str(var) + '.txt'), mode='w'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM