【问题标题】:Python - How to export each item in a list to individual text filePython - 如何将列表中的每个项目导出到单个文本文件
【发布时间】:2015-01-27 15:38:01
【问题描述】:

我有一个 csv 文件,其中包含我试图循环访问的几十个网页。

目标是从网页中获取文本,取出html标记(使用html2text),然后将干净的文本保存为.txt文件。我的想法是将每个网页的纯文本保存为列表中的一个项目,然后将列表中的每个项目导出到一个 txt 文件。

我可以让程序遍历 url 并取出 html,但保存到单个 txt 文件时会不断抛出错误。谁能给我一些关于如何做到这一点的想法?

代码:

from stripogram import html2text
import urllib
import csv

text_list = []
urls = csv.reader(open('web_links2.csv'))

for url in urls:
    response = urllib.urlopen(url[0])
    html = response.read()
    text = html2text(html)
    text_list.append(text)

print text_list

for item in text_list:
    f = open('c:\users\jacob\documents\txt_files\%s.txt'%(item,), 'w')
    f.write(item)
    f.close

【问题讨论】:

  • 抛出的错误是什么,发生在哪里?

标签: python loops csv web-scraping output


【解决方案1】:

看起来您对文件名及其内容使用了相同的值 (item),因此除非这些文件是单个单词,否则您很可能会生成非法文件名。

另外,为了调用close,您需要提供括号。

【讨论】:

    【解决方案2】:

    您的主要问题是您没有转义 t 使用原始字符串 r

    open(r'c:\users\jacob\documents\txt_files\%s.txt'%(item,), 'w')
    

    \t 是制表符,因此请使用示例中的原始字符串,在文件路径中使用双 \\ 或正斜杠 /

    In [11]: s = "\txt_files"
    
    In [12]: print(s)
        xt_files
    
    In [13]: s = r"\txt_files"
    
    In [14]: print(s)
    \txt_files
    
    
    f.close <- missing parens to call the method
    

    使用 with 打开文件,忘记调用 close 之类的事情不会成为问题:

    with open(r'c:\users\jacob\documents\txt_files\%s.txt'%(item,), 'w') as f: # closes your files automatically
        f.write(item)
    

    【讨论】:

      【解决方案3】:

      我认为您可能不想将完整项目添加到文件名中,因为该项目是网页的所有 html。在你的情况下,我要么添加一些逻辑来给它一个整洁的网站名称,要么只使用一个索引,这样你就可以遍历它。

      另外文件路径定义应该不同,尽量用双引号和\代替. 你可能想做这样的事情:

      i = 0
      for item in text_list:
          i += 1
          #also use format instead of the %s
          f = open("c:\\users\\jacob\\documents\\txt_files\\{0}.txt".format(i), 'w')
          f.write(item)
          f.close()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-27
        • 1970-01-01
        • 2017-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多