第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

循環(huán)運(yùn)行python腳本并將輸出打印到文件

循環(huán)運(yùn)行python腳本并將輸出打印到文件

白衣非少年 2021-11-23 20:07:01
我有以下 python 腳本:import somethingresponse = requests.get('https://example.com/folder/1')data = stuff_hereprint(data)我想為 URL 值 1 到 100 運(yùn)行此腳本并將輸出保存到1.txt, 2.txt ... 100.txt。任何想法我怎么能做到這一點(diǎn)?
查看完整描述

2 回答

?
慕的地8271018

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個贊

這應(yīng)該可以解決問題:


# Firstly you import what you need to import

import something


# For-loop which runs from values 1 to 101 (101 is non-inclusive)

# with each value being stored in to 'i'

for i in range(1, 101):

    # Runs requests.get() method on the URL

    # URL is made by f-formatting a string ('{i}' will get replaced with the value of 'i')

    response = requests.get(f'https://example.com/folder/{i}')


    # Does 'stuff_here' and stores it in 'data'

    data = stuff_here


    # Prints out data

    print(data)


    # with keyword opens the file f'{i}.txt' in "w" mode,

    #  and stores is in to the 'file' variable.

    # f'{i}.txt' is, again, an f-formatted string which replaces '{i}' with the value of i

    # "w" mode is writing mode, you can write to a file while using it

    with open(f"{i}.txt", "w") as file:

        # Writes the contents of 'data' to the file 'file'

        file.write(data)


查看完整回答
反對 回復(fù) 2021-11-23
?
偶然的你

TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個贊

像這樣的東西:


import requests



input_list = []


for i in range(1, 101):

    input_list.append(('https://example.com/folder/{}'.format(i), "{}.txt".format(i)))



for input_ in input_list:

    req = requests.get(input_[0])

    if (req.status_code == 200):

        result = req.text

    else:

        result = "Failed Request {}".format(req.status_code)

    with open(input_[1], "w") as f:

        f.write(result)


查看完整回答
反對 回復(fù) 2021-11-23
  • 2 回答
  • 0 關(guān)注
  • 316 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號