我一直在研究刮刀,从网站上获取大量的HTML和图像.我的刮刀工作正常,但目录大量填充,导致难以导航.我如何将其保存到子目录?保存HTML的部分:
t = open(str(current)+".html", 'w+')
t.write(b)
t.close()
Run Code Online (Sandbox Code Playgroud)
以及保存图像的部分:
urllib.request.urlretrieve(img, page+".gif")
Run Code Online (Sandbox Code Playgroud)
您只向我们展示了一些无用的代码,其中说写入子目录很简单,但首先需要创建一个.现在,我只能给你一些基本的例子,因为我不知道你的代码的其余部分是什么样的,希望这里有些帮助!
def create_folder(self, path):
try:
if os.path.isdir(path):
print("Error: The directory you're attempting to create already exists") # or just pass
else:
os.makedirs(path)
except IOError as exception:
raise IOError('%s: %s' % (path, exception.strerror))
return None
Run Code Online (Sandbox Code Playgroud)
甚至更容易
os.makedirs("C:\\Example Folder\\")
Run Code Online (Sandbox Code Playgroud)
或者在Linux的情况下
os.makedirs('/home/' + os.getlogin() + '/Example Folder/')
Run Code Online (Sandbox Code Playgroud)
然后像往常一样写入它,就像提供子目录的路径一样.
def write(self, path, text):
try:
if os.path.isfile(path):
return None # or print and error, or pass etc...
else:
with open(path, 'w') as outFile:
outFile.write(text)
except IOError as exception:
raise IOError("%s: %s" % (path, exception.strerror))
return None
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您将路径放在"path"参数中的子目录和包含"text"参数中的文本的变量中.您可以修改此函数以追加,写入字节等.
更新了解决您意见的信息
使小型python程序"更多"跨平台的一种非常简单的方法就是做一些类似的事情
if sys.platform == 'win32':
print('This is windows')
elif sys.platform == 'linux2':
print('This is some form of linux')
Run Code Online (Sandbox Code Playgroud)
您可以添加它来检查操作系统,然后根据操作系统运行您的块:)
是的,你是正确的,上面的写功能会覆盖文件,你可以通过将'w'标志更改为'a'来附加文件(添加新文本而不覆盖现有文本)
def append(self, path, text):
try:
if os.path.isfile(path):
with open(path, 'a') as outFile:
outFile.write(text)
except IOError as exception:
raise IOError('%s: %s' % (path, exception.strerror))
return None
Run Code Online (Sandbox Code Playgroud)
进一步更新:
如果您不使用课程,可以删除"self".
基于你最后的评论"我自己放了什么"我非常强烈建议你暂时放弃你的项目并首先学习python的基础知识......你可以在以下地方找到各种教程.
https://www.tutorialspoint.com/python/
https://docs.python.org/3/tutorial/
如果您使用的是旧版本,您可以简单地更改为您在官方网站上使用的任何一个版本,我祝您好运,但不幸的是,如果不首先了解基本知识,我无法帮助您, '对不起!
更新:这是很久以后的事情,但我觉得有必要将这些添加到答案中,因为这篇文章最近再次被查看.
os.mkdir('\path\to\dir')
# is also valid
# Python 3+ use the following
if sys.platform.startswith('linux'):
print('This is linux')
#insert code here. We use .startswith('')
#becuase the version number was depricated
elif sys.platform.startswith('win'):
print('This is windows')
Run Code Online (Sandbox Code Playgroud)