python循环附加所有内容

问题描述 投票:0回答:1

以下代码将每个迭代附加到下一个。每个文件应约有50个玩家,但文件名组1为50,文件名组2为100(team1 + team2),依此类推。如何只用year + team的1次迭代创建单个文件。

from nfl_fun import make_soup
import os
from itertools import islice
import csv
from datetime import datetime

years = [2019,2018,2017,2016,2015]

year = datetime.now().year

if year not in years:
    years.append(year)

linkname = ""


with open("teamlink.csv") as tl:

    for row in islice(csv.reader(tl), 1, None):
        for season in years:
            rowlink = f"https://www.footballdb.com/{row[0]}/roster/{season}"
            soup = make_soup(rowlink)
            try:
                for boot in soup.findAll('b'):

                    for link in boot.findAll('a'):

                        if link.has_attr('href'):
                            linkname = linkname + "\n" + (link.attrs['href'])[1:]

                            userfile = f"{rowlink[37:-12]}-{season}"
                            header="Links"
                            file = open(os.path.expanduser(f"{userfile}.csv"), "wb")
                            file.write(bytes(header, encoding="ascii", errors='ignore'))
                            file.write(bytes(linkname, encoding="ascii",errors='ignore'))
                            file.close()

            except:
                continue
python loops
1个回答
0
投票

每次更换团队时都需要重置linkname,只需添加

linkname = ""

file.close()之后或类似内容。

© www.soinside.com 2019 - 2024. All rights reserved.