【问题标题】:Unable to put different text files creating different subfolders within a main folder无法将不同的文本文件放在主文件夹中创建不同的子文件夹
【发布时间】:2019-06-25 17:16:16
【问题描述】:

我用 python 编写了一个脚本,从网页上抓取不同帖子的前五个标题,然后将标题写入单独的文本文件中,并将它们放在桌面文件夹 DataStorage 内的五个不同子文件夹中。

目前我的以下脚本可以解析五篇文章的标题,并将它们写在五个不同的文本文件中,并将它们放在桌面文件夹DataStorage

如何在一个主文件夹中创建五个不同的子文件夹,并将文本文件放在相关的子文件夹中?

这是我目前的尝试:

import os
import requests
from bs4 import BeautifulSoup

url = "https://stackoverflow.com/questions/tagged/web-scraping"

dirf = r"C:\Users\WCS\Desktop\DataStorage" #The main folder in desktop
if not os.path.exists(dirf):os.makedirs(dirf)
os.chdir(dirf)

res = requests.get(url)
soup = BeautifulSoup(res.text,"lxml")
for item in soup.select(".summary .question-hyperlink")[:5]:
    filename = item.text.split(" ")[0]
    with open(filename+'.txt','w', encoding='utf-8') as filename:
        filename.write(item.text)

【问题讨论】:

    标签: python python-3.x web-scraping directory subdirectory


    【解决方案1】:

    要创建目录,您可以使用os.mkdir(PATH)。要创建文件,您可以open 具有w+ 权限的文件,如果文件不存在则创建文件,如果文件存在则重写文件。

    【讨论】:

      【解决方案2】:

      以下可能有效

      import os
      import requests
      from bs4 import BeautifulSoup
      
      url = "https://stackoverflow.com/questions/tagged/web-scraping"
      
      dirf = r"C:\Users\WCS\Desktop\DataStorage"  # The main folder in desktop
      if not os.path.exists(dirf):
          os.makedirs(dirf)
      os.chdir(dirf)
      
      res = requests.get(url)
      soup = BeautifulSoup(res.text, "lxml")
      for item in soup.select(".summary .question-hyperlink")[:5]:
          filename = item.text.split(" ")[0]
          curr_dir = os.path.join(dirf, filename)
          os.makedirs(curr_dir)
          filepath = os.path.join(curr_dir, filename+'.txt')
          with open(filepath, 'w', encoding='utf-8') as f:
              f.write(item.text)
      

      【讨论】:

        【解决方案3】:

        永远不要如果可以避免使用os.chdir,即:大部分时间/总是

        另外,它会阻止您了解当前目录之外的文件路径的逻辑。

        首选在您正在读取/写入的文件上使用绝对路径。

        所以删除

        os.chdir(dirf)
        

        现在改变这个:

        with open(filename+'.txt','w', encoding='utf-8') as filename:
        

        通过

        subdir = os.path.join(dirf,item)
        if os.path.exists(subdir):
            os.mkdir(subdir)   # create first time
        with open(os.path.join(subdir,filename+'.txt'),'w', encoding='utf-8') as f:
           f.write(item.text)
        

        其中item 是您的子目录相对路径(它必须符合当前的文件系统规则,因为它源自html 文件,所以不能100% 保证)。另请注意,您不应该对文件handle 再次使用filename。我通常使用ffilehandle

        【讨论】:

          猜你喜欢
          • 2013-04-14
          • 2019-05-11
          • 2023-03-20
          • 1970-01-01
          • 1970-01-01
          • 2014-08-14
          • 1970-01-01
          • 1970-01-01
          • 2020-01-13
          相关资源
          最近更新 更多