无法将新结果*first*附加到具有旧数据的现有csv文件中

2024-03-28 11:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用python编写了一个脚本,它能够从网页中获取不同文章的标题,并将它们写入csv文件。由于网站的内容更新非常频繁,我喜欢将新的结果首先附加到csv文件中,那里已经有可用的旧标题列表。你知道吗

我试过:

import csv
import time
import requests
from bs4 import BeautifulSoup

url = "https://stackoverflow.com/questions/tagged/python"

def get_information(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'lxml')
    for title in soup.select(".summary .question-hyperlink"):
        yield title.text

if __name__ == '__main__':
    while True:
        with open("output.csv","a",newline="") as f:
            writer = csv.writer(f)
            writer.writerow(['posts'])
            for items in get_information(url):
                writer.writerow([items])
                print(items)

        time.sleep(300)

上面的脚本在运行两次时可以在旧结果之后附加新结果。你知道吗

旧数据如下:

A
F
G
T

新数据是WQU。你知道吗

当我重新运行脚本时,csv文件应该如下所示:

W
Q
U
A
F
G
T

如何将新结果首先附加到包含旧数据的现有csv文件中?


Tags: 文件csv数据import脚本url标题get
2条回答

在文件的任何地方插入数据,除了在文件末尾,都需要重写整个过程。要做到这一点而不首先将其全部内容读入内存,可以创建一个包含新数据的临时csv文件,将现有文件中的数据附加到该文件中,删除旧文件并重命名新文件。你知道吗

下面是我的意思的示例(使用一个伪get_information()函数来简化测试)。你知道吗

import csv
import os
from tempfile import NamedTemporaryFile

url = 'https://stackoverflow.com/questions/tagged/python'
csv_filepath = 'updated.csv'

# For testing, create a existing file.
if not os.path.exists(csv_filepath):
    with open(csv_filepath, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerows([item] for item in 'AFGT')

# Dummy for testing.
def get_information(url):
    for item in 'WQU':
        yield item


if __name__ == '__main__':
    folder = os.path.abspath(os.path.dirname(csv_filepath))  # Get dir of existing file.

    with NamedTemporaryFile(mode='w', newline='', suffix='.csv',
                            dir=folder, delete=False) as newf:
        temp_filename = newf.name  # Save filename.
        # Put new data into the temporary file.
        writer = csv.writer(newf)
        for item in get_information(url):
            writer.writerow([item])
            print([item])

        # Append contents of existing file to new one.
        with open(csv_filepath, 'r', newline='') as oldf:
            reader = csv.reader(oldf)
            for row in reader:
                writer.writerow(row)
                print(row)

    os.remove(csv_filepath)  # Delete old file.
    os.rename(temp_filename, csv_filepath)  # Rename temporary file.

由于要更改表中每个元素的位置,因此需要将表读入内存并重写整个文件,从新元素开始。你知道吗

您可能会发现:(1)将新元素写入新文件;(2)打开旧文件并将其内容附加到新文件;(3)将新文件移到原始(旧)文件名更容易。你知道吗

相关问题 更多 >