Python os.mkdir 中的“没有这样的文件或目录”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27832648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"No such file or directory" from os.mkdir
提问by DANIEL REAPSOME
working on a python project, and what it does is it looks at the index of lifehacker.com, then finds all tags with the class "headline h5 hover-highlight entry-title", then it creates files for each directory. But the only problem is that when i run it, i get OSError: [Errno 2] No such file or directory: "/home/root/python/The Sony Smartwatch 3: A Runner's Perspective (Updated: 1/5/2015)"
在 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)"
help would be lovely, thanks!
帮助会很可爱,谢谢!
heres my code 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!"
采纳答案by Charles Duffy
Sanitize your filename. (Failing to do so is also going to cause you security issues, particularly if you don't prevent things from starting with ../
).
清理您的文件名。(不这样做也会给您带来安全问题,特别是如果您不阻止事情以 开头../
)。
This could be as simple as:
这可能很简单:
safe_name = i.text.replace('/', '_')
os.mkdir(os.path.join(file_directory, safe_name))
As it is, your code is trying to create a directory named 2015)
, in a directory named 5
, in a directory named The Sony Smartwatch 3: A Runner's Perspective (Updated: 1
. Since none of those exist, and os.mkdir()
isn't recursive, you get the error in question. (If you wanta recursive operation, see os.makedirs()
instead).
实际上,您的代码正在尝试在名为 的目录中创建名为2015)
的目录 在名为5
的目录中The Sony Smartwatch 3: A Runner's Perspective (Updated: 1
。由于这些都不存在,os.mkdir()
也不是递归的,你会得到有问题的错误。(如果您想要递归操作,请参阅os.makedirs()
)。