我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
当前回答
关于这种情况的具体性
您在某个路径上提供一个特定的文件,然后从文件路径中提取目录,然后确保您有目录后,您试图打开阅读的文件。
import os
filepath = '/my/directory/filename.txt'
directory = os.path.dirname(filepath)
你的最终目标是打开这个文件,你最初表示,写作,但你基本上接近这个目标(基于你的代码),如此,打开文件阅读:
如果不是 os.path.exists(地址): os.makedirs(地址) f = 文件(文件名)
為什麼你會為你期望在那裡並能夠閱讀的檔案製作一個目錄?
只是试着打开文件。
with open(filepath) as my_file:
do_stuff(my_file)
import errno
try:
with open(filepath) as my_file:
do_stuff(my_file)
except IOError as error:
if error.errno == errno.ENOENT:
print 'ignoring error because directory or file is not there'
else:
raise
假设我们对写作开放
在这种情况下,我们可能不会遇到任何竞赛条件,所以只是做你是,但请注意,写作,你需要打开W模式(或一个添加)。
import os
if not os.path.exists(directory):
os.makedirs(directory)
with open(filepath, 'w') as my_file:
do_stuff(my_file)
import os
import errno
if not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError as error:
if error.errno != errno.EEXIST:
raise
with open(filepath, 'w') as my_file:
do_stuff(my_file)
其他回答
在您的程序/项目的输入点上拨打 Create_dir() 函数。
import os
def create_dir(directory):
if not os.path.exists(directory):
print('Creating Directory '+directory)
os.makedirs(directory)
create_dir('Project directory')
我个人建议您使用 os.path.isdir() 测试而不是 os.path.exists()。
>>> os.path.exists('/tmp/dirname')
True
>>> os.path.exists('/tmp/dirname/filename.etc')
True
>>> os.path.isdir('/tmp/dirname/filename.etc')
False
>>> os.path.isdir('/tmp/fakedirname')
False
如果你有:
>>> directory = raw_input(":: ")
一个愚蠢的用户输入:
:: /tmp/dirname/filename.etc
... 您将以 filename.etc 命名的目录结束,当您将该论点转移到 os.makedirs(),如果您使用 os.path.exists()进行测试。
import pathlib
pathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True)
pathlib.Path.mkdir 如上所述,重复创建目录,如果目录已经存在,则不会产生例外。
Python 3.2 以上:
使用Pathlib:
使用我们:
import os
os.makedirs(path, exist_ok=True)
使用Pathlib:
使用我们:
import os
try:
os.makedirs(path)
except OSError:
if not os.path.isdir(path):
raise
请注意,捕获例外和使用 errno 是有限的用途,因为 OSError: [Errno 17] 文件存在,即 errno.EEXIST,为文件和目录上传。
替代品:
import distutils.dir_util
distutils.dir_util.mkpath(path)
换句话说,如果您使用它创建一个目录,然后从内部或外部的目录删除,然后再使用目录重新创建相同的目录,目录将简单地沉默地使用其未成效的隐藏信息之前创建的目录,并将不起作用。
至于目录模式,请参考文档,如果您对此感兴趣。
我下载了下面的文章,但这不是完全愚蠢的。
import os
dirname = 'create/me'
try:
os.makedirs(dirname)
except OSError:
if os.path.exists(dirname):
# We are nearly safe
pass
else:
# There was an error on creation, so make sure we know about it
raise
如今,正如我所说的那样,这不是真正的愚蠢,因为我们有可能无法在那个时期创建目录,还有另一个创建过程。
如果您正在写一个文件到一个变量路径,您可以在文件路径上使用此文件,以确保母目录创建。
from pathlib import Path
path_to_file = Path("zero/or/more/directories/file.ext")
parent_directory_of_file = path_to_file.parent
parent_directory_of_file.mkdir(parents=True, exist_ok=True)
工作,即使 path_to_file 是 file.ext (零目录深)。
查看 pathlib.PurePath.parent 和 pathlib.Path.mkdir。