"没有这样的文件或目录"来自os.mkdir

时间:2015-01-08 03:55:09

标签: python beautifulsoup

在python项目上工作,它的作用是查看lifehacker.com的索引​​,然后查找所有标题为“headline h5 hover-highlight entry-title”的类,然后为每个目录创建文件。但唯一的问题是,当我运行它时,我得到OSError: [Errno 2] No such file or directory: "/home/root/python/The Sony Smartwatch 3: A Runner's Perspective (Updated: 1/5/2015)"

帮助会很可爱,谢谢!

继承我的代码atm:

import re
import os
import urllib2
from bs4 import BeautifulSoup
from mechanize import Browser

url = "http://lifehacker.com/"
url_open = urllib2.urlopen(url)
soup = BeautifulSoup(url_open.read())

link = soup.findAll("h1",{"class": "headline h5 hover-highlight entry-title"})
file_directory = "/home/root/python/"

for i in link:
    os.mkdir(os.path.join(file_directory, str(i.text)))
    print "Successfully made directory(s)", i.text, "!"
else:
    print "The directory", i.text, "either exists, or there was an error!"

1 个答案:

答案 0 :(得分:5)

清理文件名。 (如果不这样做也会导致安全问题,特别是如果你不阻止事情从../开始)。

这可以很简单:

safe_name = i.text.replace('/', '_')
os.mkdir(os.path.join(file_directory, safe_name))

实际上,您的代码正在尝试在名为2015)的目录中的名为5的目录中创建名为The Sony Smartwatch 3: A Runner's Perspective (Updated: 1的目录。由于这些都不存在,并且os.mkdir()不是递归的,因此您会收到有问题的错误。 (如果您想要递归操作,请参阅os.makedirs()