Skip to main content
 首页 » 编程设计

python之如何使用 Python 读取目录中的所有 HTML 文件并将内容写入 CSV 文件

2024年11月01日13Renyi-Fan

我正在尝试读取目录中的所有 HTML 文件并将它们写入 CSV 文件。 CSV 文件中的每一行将包含一个 HTML 文件的内容。

我似乎能够读取一个 HTML 文件并写入一个 CSV 文件。

import os, csv 
import fnmatch 
from pathlib import Path 
 
directory = "directory/" 
 
for dirpath, dirs, files in os.walk(directory): 
    for filename in fnmatch.filter(files, '*.html'): 
        with open(os.path.join(dirpath, filename)) as f: 
            html = f.read() 
            if 'apples and oranges' in html: 
                with open('output.csv', 'w') as f: 
                    writer = csv.writer(f) 
                    lines = [[html]] 
                    for l in lines: 
                        writer.writerow(l) 

我目前只看到一个 HTML 文件被打印到一个 CSV 行中。

请您参考如下方法:

因为你用了'w' or write mode .

with open('output.csv', 'w') as f: 

这会截断文件并覆盖之前的内容。

你应该使用 'a' or append mode .

with open('output.csv', 'a') as f: 

如果文件不存在则打开文件进行写入,如果文件已存在则附加到文件末尾。