Как сохранить вывод в текстовый файл для скрипта Python? - PullRequest
0 голосов
/ 03 марта 2010

Я пытаюсь сделать так, чтобы этот сценарий

from BeautifulSoup import BeautifulSoup
import sys, re, urllib2
import codecs

html_str = urllib2.urlopen(URL).read()

soup = BeautifulSoup(html_str)

for row in soup.findAll("tr"): 
  for col in row.findAll(re.compile("td|th")):
    for 
    sys.stdout.write((col.string if col.string else '') + '|') 
  print # Newline

отправляет вывод в текстовый файл.

1 Ответ

4 голосов
/ 03 марта 2010

Самый простой? (если * nix): -

python file.py > filename.txt

Код мудрый, хотя: -

from BeautifulSoup import BeautifulSoup
import sys, re, urllib2
import codecs

html_str = urllib2.urlopen(URL).read()

soup = BeautifulSoup(html_str)

file = open('file.txt', 'w')

for row in soup.findAll("tr"): 
  for col in row.findAll(re.compile("td|th")):
    file.write((col.string if col.string else '') + '|') 

file.close()
...