我用 python 编写了一个脚本,从网页上抓取不同帖子的前五个标题,然后将标题写入单独的文本文件,并将它们放在桌面文件夹中的五个不同子文件夹中DataStorage。目前我的以下脚本可以解析五个帖子的标题并将它们写入五个不同的文本文件中,然后将它们放在桌面文件夹中DataStorage。如何在一个主文件夹中创建五个不同的子文件夹并将文本文件放在相关的子文件夹中?到目前为止,这是我的尝试:import osimport requestsfrom bs4 import BeautifulSoupurl = "https://stackoverflow.com/questions/tagged/web-scraping"dirf = r"C:\Users\WCS\Desktop\DataStorage" #The main folder in desktopif 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)
3 回答

肥皂起泡泡
TA贡献1829条经验 获得超6个赞
要创建目录,您可以使用os.mkdir(PATH)
. 要创建文件,您可以open
使用具有w+
权限的文件,如果文件不存在则创建该文件,如果存在则重写该文件。

精慕HU
TA贡献1845条经验 获得超8个赞
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% 保证)。另请注意,您不应filename再次使用文件句柄。我通常使用f或filehandle
添加回答
举报
0/150
提交
取消