Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-如何将列表中的每个项目导出到单个文本文件_Python_Loops_Csv_Web Scraping_Output - Fatal编程技术网

Python-如何将列表中的每个项目导出到单个文本文件

Python-如何将列表中的每个项目导出到单个文本文件,python,loops,csv,web-scraping,output,Python,Loops,Csv,Web Scraping,Output,我有一个包含几十个网页的csv文件,我正试图循环浏览这些网页 目标是从网页中获取文本,取出html标记(使用html2text),然后将干净的文本保存为.txt文件。我的想法是将每个网页的干净文本保存为列表中的一个项目,然后将列表中的每个项目导出为txt文件 我可以让程序在URL上循环并取出html,但是保存到单个txt文件会不断抛出错误。有人能给我一些关于如何做这件事的想法吗 代码: 看起来您对文件名及其内容使用了相同的值(item),因此,除非这些文件是单个单词,否则可能会生成非法的文件名

我有一个包含几十个网页的
csv
文件,我正试图循环浏览这些网页

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

我可以让程序在URL上循环并取出html,但是保存到单个txt文件会不断抛出错误。有人能给我一些关于如何做这件事的想法吗

代码:


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


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

我认为您可能不想将完整项添加到文件名中,因为该项都是网页的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()

您的主要问题是您没有逃逸
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

抛出的错误是什么,发生在哪里?
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 open(r'c:\users\jacob\documents\txt_files\%s.txt'%(item,), 'w') as f: # closes your files automatically
    f.write(item)