gpt4 book ai didi

python - CSV Writer 覆盖自身

转载 作者:太空宇宙 更新时间:2023-11-04 09:17:19 26 4
gpt4 key购买 nike

我正在尝试创建一个包含 URL 列表的 CSV 文件。

我是编程新手,所以请原谅任何草率的代码。

我有一个循环遍历位置列表以获取 URL 列表。

然后我在该循环中有一个循环将数据导出到 CSV 文件。

import urllib, csv, re
from BeautifulSoup import BeautifulSoup
list_of_URLs = csv.reader(open("file_location_for_URLs_to_parse"))
for row in list_of_URLs:
row_string = "".join(row)
file = urllib.urlopen(row_string)
page_HTML = file.read()
soup = BeautifulSoup(page_HTML) # parsing HTML
Thumbnail_image = soup.findAll("div", {"class": "remositorythumbnail"})
Thumbnail_image_string = str(Thumbnail_image)
soup_3 = BeautifulSoup(Thumbnail_image_string)
Thumbnail_image_URL = soup_3.findAll('a', attrs={'href': re.compile("^http://")})

这是对我不起作用的部分:

    out  = csv.writer(open("file_location", "wb"), delimiter=";")
for tag in soup_3.findAll('a', href=True):
out.writerow(tag['href'])

基本上作者一直在写自己,有没有办法跳到 CSV 上第一个空行的下方并开始写作?

最佳答案

不要把它放在任何循环中:

out  = csv.writer(open("file_location", "wb"), delimiter=";")

相反:

with open("file_location", "wb") as fout:
out = csv.writer(fout, delimiter=";")
# put for-loop here

注意事项:

  1. open("file_location", "wb") 创建一个新文件,销毁所有同名的旧文件。这就是为什么它看起来作者正在覆盖旧行。
  2. 使用with open(...) as ...因为它会自动关闭文件当 with-block 结束时为您服务。这在文件关闭时是明确的。否则,文件将保持打开状态(并且可能不会完全刷新),直到 out 被删除或重新分配给新值。这并不是您的主要问题,但是使用 with 非常有用,更不用说了。

关于python - CSV Writer 覆盖自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7585909/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com