我试图写入一个csv文件,为此我必须将一些存储在不同变量中的值传递给writerrow方法,但当我尝试这样做时,我总是得到这个错误:
'语法错误:右括号")"与左括号"{""不匹配。
我已经尝试过使用老式的方法" % s",但错误仍然相同。下面是我尝试实现f string方法的代码:
import csv
import matplotlib.pyplot as plt
specialists = {'ST', 'LS', 'KR', 'PR', 'K', 'P'}
AFC_North = [0, {'CIN', 'BAL', 'CLE', 'PIT'}, 'AFC North']
AFC_East = [0, {'NWE', 'BUF', 'MIA', 'NYJ'}, 'AFC East']
AFC_West = [0, {'KAN', 'LAC', 'DEN', 'LVR'}, 'AFC West']
AFC_South = [0, {'HOU', 'JAX', 'TEN', 'IND'}, 'AFC South']
NFC_North = [0, {'GNB', 'MIN', 'DET', 'CHI'}, 'NFC North']
NFC_East = [0, {'PHI', 'DAL', 'WAS', 'NYG'}, 'NFC East']
NFC_West = [0, {'LAR', 'ARI', 'SEA', 'SFO'}, 'NFC West']
NFC_South = [0, {'TAM', 'NOR', 'CAR', 'ATL'}, 'NFC South']
AFC = [AFC_North, AFC_East, AFC_West, AFC_South]
NFC = [NFC_North, NFC_East, NFC_West, NFC_South]
## Writting
with open("All-Pros_1970-2022", 'w', newline="") as csvfile:
fieldnames = ['Div', 'Yr', 'AP']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
def wdraft(draft_year):
with open(f'csvs/AP{draft_year}.csv', 'r+') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
if 'AP: 1st Tm' in row['All-pro teams'] or 'AP: 2nd Tm' in row['All-pro teams'] and row['Pos'] not in specialists:
for i in range(len(AFC)):
if row['Tm'] in AFC[i][1]:
AFC[i][0] += 1
elif row['Tm'] in NFC[i][1]:
NFC[i][0] += 1
## Handling two teams in a season case
if '2TM' in row['Tm']:
print(row['Player'])
exc = int(input("Where do you want to put him?\n 0-8 (AFC-NFC, N,E,W,S)"))
if exc == 0:
AFC_North[0] +=1
elif exc == 1:
AFC_East[0] +=1
elif exc == 2:
AFC_West[0] +=1
elif exc == 3:
AFC_South[0] +=1
elif exc == 4:
NFC_North[0] +=1
elif exc == 5:
NFC_East[0] +=1
elif exc == 6:
NFC_West[0] +=1
elif exc == 7:
NFC_South[0] +=1
for i in AFC:
row = {
'Div': f"{ i[2] }",
'Yr': f"{ draft_year }",
'AP': f"{ i[0] }"
}
writer.writerow(row)
for i in NFC:
row = {
'Div': f"{ i[2] }",
'Yr': f"{ draft_year }",
'AP': f"{ i[0] }"
}
writer.writerow(row)
return f'{draft_year} was succesfully loaded'
print(wdraft(2022))
有什么方法可以传递一个类似于参数的f字符串或smth吗?
1条答案
按热度按时间twh00eeo1#
核心问题是你定义的函数是for循环的中间,这有点混乱,让我们把它移出for循环,稍微清理一下,让它只负责数据加载,一旦数据加载完毕,我们就可以把它写出来了。
请注意,这是未经测试的,因为我不知道您的输入数据是什么样子的: