简体   繁体   English

如何在Python中为每个ID打印到.csv

[英]how do you print to .csv for each ID in Python

import urllib
import re
import csv

player_code = open("Desktop/OHL PYTHON/test2.txt").read()

player_code = player_code.split("\r")

for pc in player_code:
    htmlfile = urllib.urlopen( "http://www.eliteprospects.com/iframe_player_stats_small.php?player="+pc+"")

    htmltext = htmlfile.read()  
    regex = '<font color="#000099">(.+?)</font>'  
    pattern = re.compile(regex)
    team = re.findall(pattern,htmltext)
    data = pc, team


    with open('my_games.csv', 'w') as csvfile:
        fieldnames = ['pc', 'team','League', 'Gp', 'G','A','P','Pims']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames,delimiter= ":",
                                extrasaction ='ignore')
        i=0
        writer.writeheader()
        for pc in player_code:
            writer.writerow({'pc':[pc],'team':[team]})
            i+=1

This is only returning one line of data over and over. 这只是一遍又一遍地返回一行数据。 Any direction would be helpful! 任何方向都会有所帮助! Thank you. 谢谢。

You should open file before the for loop or use a+ mode. 您应该在for循环之前打开文件或使用a+模式。 w opens the file and truncate its data each time it is opened. w打开文件并在每次打开时截断其数据。

with open('my_games.csv', 'w') as csvfile:
    for pc in player_code:

or 要么

with open('my_games.csv', 'a+') as csvfile

Opening file once would be a better approach. 打开文件一次是更好的方法。

Since you are looping twice for writing data you have multiple lines. 由于您为了写入数据而循环两次,因此您有多行。 Just remove 只需删除

i=0
for pc in player_code:
    writer.writerow({'pc':[pc],'team':[team]})
        i+=1

And instead just have and i think it will work. 而只是拥有,我认为它会起作用。

writer.writerow({'pc':[pc],'team':[team]})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM