Python:将多个变量写入文件

Python:将多个变量写入文件,python,beautifulsoup,python-requests,Python,Beautifulsoup,Python Requests,我对Python相当陌生,我已经编写了一个scraper,它可以按照我需要的方式打印数据,但是我在将数据写入文件时遇到了问题。我需要它看起来完全相同的方式,并在同一顺序,因为它是在空闲打印 import requests import re from bs4 import BeautifulSoup year_entry = raw_input("Enter year: ") week_entry = raw_input("Enter week number: ") week_link =

我对Python相当陌生,我已经编写了一个scraper,它可以按照我需要的方式打印数据,但是我在将数据写入文件时遇到了问题。我需要它看起来完全相同的方式,并在同一顺序,因为它是在空闲打印

import requests
import re
from bs4 import BeautifulSoup

year_entry = raw_input("Enter year: ")

week_entry = raw_input("Enter week number: ")

week_link = requests.get("http://sports.yahoo.com/nfl/scoreboard/?week=" + week_entry + "&phase=2&season=" + year_entry)

page_content = BeautifulSoup(week_link.content)

a_links = page_content.find_all('tr', {'class': 'game link'})

for link in a_links:
        r = 'http://www.sports.yahoo.com' + str(link.attrs['data-url'])
        r_get = requests.get(r)
        soup = BeautifulSoup(r_get.content)
        stats = soup.find_all("td", {'class':'stat-value'})
        teams = soup.find_all("th", {'class':'stat-value'})
        scores = soup.find_all('dd', {"class": 'score'})

        try:
                game_score = scores[-1]
                game_score = game_score.text
                x = game_score.split(" ")
                away_score = x[1]
                home_score = x[4]
                home_team = teams[1]
                away_team = teams[0]
                away_team_stats = stats[0::2]
                home_team_stats = stats[1::2]
                print away_team.text + ',' + away_score + ',',
                for stats in away_team_stats:
                        print stats.text + ',',
                print '\n'
                print home_team.text + ',' + home_score +',',
                for stats in home_team_stats:
                        print stats.text + ',',
                print '\n'

        except:
                pass
我完全搞不懂如何让它以空闲打印的方式打印到txt文件。该代码只在NFL赛季的最后几周运行。因此,如果您测试代码,我建议年份=2014,周=12(或之前)

谢谢


JT

要写入文件,需要将该行构建为字符串,然后将该行写入文件

您可以使用以下内容:

# Open/create a file for your output   
with open('my_output_file.csv', 'wb') as csv_out:
    ...
    # Your BeautifulSoup code and parsing goes here
    ...
    # Then build up your output strings
    for link in a_links: 
        away_line = ",".join([away_team.text, away_score])
        for stats in away_team_stats:
            away_line += [stats.text]
        home_line = ",".join(home_team.text, home_score])
        for stats in home_team_stats:
                home_line += [stats.text]

        # Write your output strings to the file   
        csv_out.write(away_line + '\n')
        csv_out.write(home_line + '\n')

这是一个快速而肮脏的解决办法。为了正确地完成这项工作,您可能需要从输出的结构中查看
csv
模块()

,我同意Jamie的观点,使用csv是一种合乎逻辑的选择

但由于您使用的是Python2,所以可以使用另一种形式的print语句打印到文件中

print还有一个扩展表单,由 上面描述的语法。此表格有时称为“打印” 在这种形式中,>>后面的第一个表达式必须 计算为“类似文件”的对象,特别是具有 如上所述的write()方法。通过这种扩展形式 后续表达式将打印到此文件对象。如果第一个 表达式的计算结果为无,则sys.stdout用作 输出

例如

但是,Python 3不支持这种语法,因此我想使用它可能不是一个好主意。:)FWIW,在写入文件时,我通常在代码中使用file write()方法,但对于错误消息,我倾向于使用
print>>sys.stderr

outfile = open("myfile.txt", "w")
print >>outfile, "Hello, world"
outfile.close()