我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
当前回答
我个人建议您使用 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()进行测试。
其他回答
检查是否有一个目录,并在需要时创建它。
if not os.path.exists(d):
os.makedirs(d)
import errno
try:
os.makedirs(d)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
import tempfile
d = tempfile.mkdtemp()
有一个新的路径对象(如3.4)与许多方法,你会想使用路径 - 其中一个是 mkdir。
首先,相关进口:
from pathlib import Path
import tempfile
我们不需要处理 os.path.join 现在 - 只是加入路径部分与一个 /:
directory = Path(tempfile.gettempdir()) / 'sodata'
然后我无力地确保目录存在 - 存在_ok 论点在 Python 3.5 中出现:
directory.mkdir(exist_ok=True)
下面是文档的相关部分:
如果 exist_ok 是真实的,FileExistsError 例外将被忽略(与 POSIX mkdir -p 命令相同的行为),但只有如果最后的路径组件不是现有的非指南文件。
todays_file = directory / str(datetime.datetime.utcnow().date())
if todays_file.exists():
logger.info("todays_file exists: " + str(todays_file))
df = pd.read_json(str(todays_file))
路径对象必须在等待路径可以使用的其他API之前被强迫到Str。
也许Pandas应该更新以接受抽象基础类,os.PathLike的例子。
相关的 Python 文档建议使用 EAFP 编码风格(更容易要求宽恕而不是允许)。
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
else:
print "\nBE CAREFUL! Directory %s already exists." % path
比替代品更好
if not os.path.exists(path):
os.makedirs(path)
else:
print "\nBE CAREFUL! Directory %s already exists." % path
文档表明这一点正是因为在这个问题上讨论的竞赛条件。 此外,正如其他人在这里提到的那样,在询问一次而不是两次操作系统时,有一个性能优势。 最后,在某些情况下,潜在地提前提出的论点 - 当开发人员知道应用程序正在运行的环境时 - 只能在
即使在這種情況下,這是一個糟糕的做法,可能會導致漫長的無用解散。 例如,我們設定的許可證的目錄不應該讓我們與印刷許可證是適當設定的我們的目的。 一個母目錄可以與其他許可證。
在创建目录之前,您必须设置完整的路径:
import os,sys,inspect
import pathlib
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
your_folder = currentdir + "/" + "your_folder"
if not os.path.exists(your_folder):
pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)
这对我工作,我希望这对你也工作。
关于这种情况的具体性
您在某个路径上提供一个特定的文件,然后从文件路径中提取目录,然后确保您有目录后,您试图打开阅读的文件。
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)
我使用os.path.exists(),这里是一个Python 3脚本可以用来检查是否有一个目录,创建一个如果它不存在,并删除它如果它存在(如果需要)。
它鼓励用户输入目录,并且可以轻松修改。