繁体   English   中英

Python:将多个变量写入文件

[英]Python: Writing multiple variables to a file

我是Python的新手,我编写了一个刮板,可以按我需要的确切方式打印数据,但是我在将数据写入文件时遇到了麻烦。 我需要它看起来与在IDLE中打印时完全一样的方式和顺序

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

我完全困惑如何使它以在IDLE中打印的相同方式打印到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模块( docs

从输出的结构中,我同意Jamie的观点,即使用CSV是合乎逻辑的选择。

但是,由于您使用的是Python 2,因此可以使用另一种形式的print语句来打印到文件。

来自https://docs.python.org/2/reference/simple_stmts.html#the-print-statement

print也具有扩展形式,由上述语法的第二部分定义。 这种形式有时称为“打印人字形”。在这种形式中,>>后面的第一个表达式必须计算为“文件状”对象,特别是具有上述write()方法的对象。 使用此扩展格式,后续表达式将打印到此文件对象。 如果第一个表达式的计算结果为“无”,则sys.stdout用作输出文件。

例如,

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

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

暂无
暂无

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

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