猿问

循环运行python脚本并将输出打印到文件

我有以下 python 脚本:


import something

response = requests.get('https://example.com/folder/1')

data = stuff_here

print(data)

我想为 URL 值 1 到 100 运行此脚本并将输出保存到1.txt, 2.txt ... 100.txt。


任何想法我怎么能做到这一点?


白衣非少年
浏览 292回答 2
2回答

慕的地8271018

这应该可以解决问题:# Firstly you import what you need to importimport 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)

偶然的你

像这样的东西:import requestsinput_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)
随时随地看视频慕课网APP

相关分类

Python
我要回答