Python 将打印但不写入.csv

Python 将打印但不写入.csv,python,python-3.x,csv,Python,Python 3.x,Csv,我已经完成了这个测试,并打印了整个脚本,在本赛季的每一场比赛中,它都会通过每一个at-bat。Try:的唯一原因是因为allstar休息日的休息日。当我打印此文件时,底部没有writer.writerow,效果很好。一旦我取消对它的注释并尝试写入csv,它就会打印一行,而我不会写入。我已尝试在Try:和out中写入csv。。我知道我可能应该定义函数来清理这个问题,但我仍然在学习正确的写作技巧。不确定我遗漏了什么,或者什么没有正确间隔。。另一双眼睛会很棒的 请求的编辑 短版 import csv

我已经完成了这个测试,并打印了整个脚本,在本赛季的每一场比赛中,它都会通过每一个at-bat。
Try:
的唯一原因是因为allstar休息日的休息日。当我打印此文件时,底部没有
writer.writerow
,效果很好。一旦我取消对它的注释并尝试写入csv,它就会打印一行,而我不会写入。我已尝试在
Try:
和out中写入csv。。我知道我可能应该定义函数来清理这个问题,但我仍然在学习正确的写作技巧。不确定我遗漏了什么,或者什么没有正确间隔。。另一双眼睛会很棒的

请求的编辑 短版

import csv
import requests
import datetime
from pprint import pprint
import pendulum


## MLB SEASON DATES
## 2016  (4-3-16 to 10-2-16)  # 2017 (4-2-17 to 10-1-17)  # 2018 (3-29-18 to 9-30-18)

try:
## Write to csv
    outfile = open('ALL_PA_LOG_2016.csv',"w",newline='')
    writer = csv.writer(outfile)
    writer.writerow(["gamepk", "day", "month", "year", "gamedate", "res_event", "des"])

# Put in Start date and End Date Below  

    start = pendulum.datetime(2016, 4, 3)
    end = pendulum.datetime(2016, 10, 2)
    period = pendulum.period(start, end)

    for dt in period.range('days'):
        day = dt.format('DD')
        month = dt.format('MM')
        year = dt.format('YYYY')

    ## Because there is the ALL STAR BREAK, Once these dates hit the break
    ## there is no regular season game scheduled so we get a KeyError and TypeError.
    ## A Try statement was the first idea I had, could be better but this works.

        req = requests.get('http://gd.mlb.com/components/game/mlb/year_' + str(year) + '/month_' + str(month) + '/day_' + str(day) + '/miniscoreboard.json') # 
        get_gameIds = req.json()['data']['games']['game']

        for gameId in get_gameIds:
            gamepk = gameId['game_pk']

            #GET GAMES BY GAMEPK WORKING GAME 530309
            req = requests.get('https://statsapi.mlb.com/api/v1.1/game/' + str(gamepk) + '/feed/live?language=en') # ' + str(gamepk) + ' 530302
            at_bat_log = req.json()['liveData']['plays']['allPlays']

            ### GET DATE
            game_data = req.json()['gameData']
            gamedate = game_data['datetime']['originalDate']

            ### GET PARK & TEAMS
            teams = game_data['teams']
            home_team = teams['home']
            park = home_team['abbreviation']
            away = teams['away']['abbreviation']
            home = home_team['abbreviation']


            for keys in at_bat_log:
                # Result Keys
                result = keys['result']
                res_type = result['type']
                res_event = result['event']
                des = result['description']
                rbi = result['rbi']
                # End Result Keys

                # About Keys    
                about = keys['about']
                topbot = about['halfInning']
                if topbot == "bottom":
                    topbot = "B"
                if topbot == "top":
                    topbot = "T"
                inn = about['inning']
                inning = str(topbot) + str(inn)

                print(gamepk, day, month, year, gamedate, res_event, des)
##                writer.writerow[(gamepk, day, month, year, gamedate, res_event, des)]

except(KeyError,TypeError):
    pass
完整脚本

import csv
import requests
import datetime
from pprint import pprint
import pendulum


## MLB SEASON DATES
## 2016  (4-3-16 to 10-2-16)  # 2017 (4-2-17 to 10-1-17)  # 2018 (3-29-18 to 9-30-18)

try:
    ## Write to csv
    outfile = open('ALL_PA_LOG_2016.csv',"w",newline='')
    writer = csv.writer(outfile)
    writer.writerow(["gamepk", "year", "gamedate", "batter", "res_event", "inning", "pitcher_team", "pitcher",
                "pa", "ab", "h", "single", "double", "triple", "hr", "bb", "tb", "gidp", "hbp", "sh", "sf", "ibb", "k", "gb",
                "fb", "line", "rbi", "des"])

    # Put in Start date and End Date Below  


    start = pendulum.datetime(2016, 4, 3)
    end = pendulum.datetime(2016, 10, 2)
    period = pendulum.period(start, end)

    for dt in period.range('days'):
        day = dt.format('DD')
        month = dt.format('MM')
        year = dt.format('YYYY')

        ## Because there is the ALL STAR BREAK, Once these dates hit the break
        ## there is no regular season game scheduled so we get a KeyError and TypeError.
        ## A Try statement was the first idea I had, could be better but this works.

        req = requests.get('http://gd.mlb.com/components/game/mlb/year_' + str(year) + '/month_' + str(month) + '/day_' + str(day) + '/miniscoreboard.json') # 
        get_gameIds = req.json()['data']['games']['game']

        for gameId in get_gameIds:
            gamepk = gameId['game_pk']

            #GET GAMES BY GAMEPK WORKING GAME 530309
            req = requests.get('https://statsapi.mlb.com/api/v1.1/game/' + str(gamepk) + '/feed/live?language=en') # ' + str(gamepk) + ' 530302
            at_bat_log = req.json()['liveData']['plays']['allPlays']

            ### GET DATE
            game_data = req.json()['gameData']
            gamedate = game_data['datetime']['originalDate']

            ### GET PARK & TEAMS
            teams = game_data['teams']
            home_team = teams['home']
            park = home_team['abbreviation']
            away = teams['away']['abbreviation']
            home = home_team['abbreviation']


            for keys in at_bat_log:
                # Result Keys
                result = keys['result']
                res_type = result['type']
                res_event = result['event']
                des = result['description']
                rbi = result['rbi']
                # End Result Keys

                # About Keys    
                about = keys['about']
                topbot = about['halfInning']
                if topbot == "bottom":
                    topbot = "B"
                if topbot == "top":
                    topbot = "T"
                inn = about['inning']
                inning = str(topbot) + str(inn)
                # End About Keys

                # Start Count Keys
                count = keys['count']
                strike = count['strikes']
                balls = count['balls']
                pitch_total = int(str(strike)) + int(str(balls))
                total_count = str(pitch_total) + '(' + str(balls) + '-' + str(strike) + ')'
                # End Count Keys

                # Start Matchup Keys
                matchup = keys['matchup']
                batter = matchup['batter']['fullName']
                bats = matchup['batSide']['code']
                pitcher = matchup['pitcher']['fullName']
                throws = matchup['pitchHand']['code']
                # End Matchup Keys

                # Runners On Start
                runnerIndex = keys['runnerIndex']
                runnersOn = len(runnerIndex)
                # Runners On End

                # Play Events Start
                playEvents = keys['playEvents']
                for event in playEvents:
                    e_type = event['type']
                # Play Events End

                # Set up Stats
                pa = 1 # Plate appearance always 1
                ab = 0 #
                h = 0 # hit. Add 1 after 1b, 2b, 3b, hr
                single = 0 # Single
                double = 0 # Double
                triple = 0 # Triple
                hr = 0 # Home Run
                bb = 0 # Walk
                tb = 0 # total bases
                gidp = 0 # Grounded Into DP
                hbp = 0 # Hit By Pitch
                sh = 0 # Sac Bunt
                sf = 0 # Sac Fly
                ibb = 0 # Intent Walk
                k = 0 # Strikeout
                gb = 0 # Groundout
                fb = 0 # Pop Out and Flyout
                line = 0 # Lineout    
                fo = 0 # Forceout not credited with hit for fielders choice.
                batter_team = " "
                pitcher_team = " "

                if res_event == "Single":
                    single += 1 
                    h += 1
                    ab += 1
                    tb += 1
                elif res_event == "Double":
                    double += 1 
                    h += 1
                    ab += 1
                    tb += 2
                elif res_event == "Triple":
                    triple += 1 
                    h += 1
                    ab += 1
                    tb += 3
                elif res_event == "Home Run":
                    hr += 1 
                    h += 1
                    ab += 1
                    tb += 4
                elif res_event == "Walk":
                    bb += 1
                elif res_event == "Grounded Into DP":
                    gidp += 1
                    ab += 1
                elif res_event == "Hit By Pitch":
                    hbp += 1
                elif res_event == "Sac Bunt":
                    sh += 1
                elif res_event == "Sac Fly":
                    sf += 1
                elif res_event == "Intent Walk":
                    ibb += 1
                elif res_event == "Strikeout":
                    k += 1
                    ab += 1
                elif res_event == "Groundout":
                    gb += 1
                    ab += 1
                elif res_event == "Flyout":
                    fb += 1
                    ab += 1
                elif res_event == "Pop Out":
                    fb += 1
                    ab += 1
                elif res_event == "Lineout":
                    line += 1
                    ab += 1
                elif res_event == "Field Error":
                    ab += 1
                elif res_event == "Fielders Choice Out":
                    ab += 1
                elif res_event == "Forceout":
                    ab += 1
                elif res_event == "Runner Out":
                    ab += 1
                elif res_event == "Runner Out" and e_type == "pickoff":
                    pa = 0
                elif topbot == "T":
                    batter_team = str(away)
                elif topbot == "B":
                    batter_team = str(home)
                elif topbot == "T":
                    pitcher_team = str(home)
                elif topbot == "B":
                    pitcher_team = str(away)


                print(gamepk, year, gamedate, batter, res_event, inning, pitcher, pa, ab, h, single, double,
                      triple, hr, bb, tb, gidp, hbp, sh, sf, ibb, k, gb, fb, line, rbi, des)
                writer.writerow[(gamepk, year, gamedate, batter, res_event, inning, pitcher_team, pitcher,
                      pa, ab, h, single, double, triple, hr, bb, tb, gidp, hbp, sh, sf, ibb, k, gb,
                      fb, line, rbi, des)]

except(KeyError,TypeError):
    pass

假设打印正确,则以下更改应起作用:

row = [gamepk, year, gamedate, batter, res_event, inning, pitcher, pa, ab, h, single, double,
        riple, hr, bb, tb, gidp, hbp, sh, sf, ibb, k, gb, fb, line, rbi, des]

print(*row)
writer.writerow(row)
您的代码语法错误,即

writer.writerow[(......)]

这是很多代码!你能把它精简成一个吗?Shortend@chriszthank you martin,深夜/清晨脚本