Dav*_*542 1048 python directory
在os
Python 的模块中,有没有办法找到目录是否存在,例如:
>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
Run Code Online (Sandbox Code Playgroud)
phi*_*hag 1613
您正在寻找os.path.isdir
,或者os.path.exists
您不关心它是文件还是目录.
例:
import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))
Run Code Online (Sandbox Code Playgroud)
Kir*_*ser 71
很近!如果传入当前存在的目录的名称,则os.path.isdir
返回True
.如果它不存在或者它不是目录,则返回False
.
joe*_*lom 54
蟒3.4引入的pathlib
模块到标准库,它提供了一个面向对象的方法来处理的文件系统的路径:
In [1]: from pathlib import Path
In [2]: p = Path('/usr')
In [3]: p.exists()
Out[3]: True
In [4]: p.is_dir()
Out[4]: True
In [5]: q = p / 'bin' / 'vim'
In [6]: q.exists()
Out[6]: True
In [7]: q.is_dir()
Out[7]: False
Run Code Online (Sandbox Code Playgroud)
Pathlib也可以通过PyPi上的pathlib2模块在 Python 2.7 上使用.
aga*_*rs3 33
是的,使用os.path.exists()
.
sks*_*mik 23
以下代码检查代码中引用的目录是否存在,如果工作场所中不存在,则会创建一个:
import os
if not os.path.isdir("directory_name"):
os.mkdir("directory_name")
Run Code Online (Sandbox Code Playgroud)
Viv*_*han 20
我们可以检查2个内置功能
os.path.isdir("directory")
Run Code Online (Sandbox Code Playgroud)
如果指定的目录可用,它将给出布尔值true.
os.path.exists("directoryorfile")
Run Code Online (Sandbox Code Playgroud)
如果指定的目录或文件可用,它将使boolead为true.
检查路径是否为目录;
os.path.isdir("directorypath")
如果路径是目录,则将布尔值设为true
AlG*_*AlG 10
如:
In [3]: os.path.exists('/d/temp')
Out[3]: True
Run Code Online (Sandbox Code Playgroud)
可能会折腾到一个os.path.isdir(...)
可以肯定的.
只是为了提供os.stat
版本(python 2):
import os, stat, errno
def CheckIsDir(directory):
try:
return stat.S_ISDIR(os.stat(directory).st_mode)
except OSError, e:
if e.errno == errno.ENOENT:
return False
raise
Run Code Online (Sandbox Code Playgroud)
小智 7
os为您提供了许多这些功能:
import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in) #gets you a list of all files and directories under dir_in
Run Code Online (Sandbox Code Playgroud)
如果输入路径无效,listdir将抛出异常.
Source,如果它仍然存在于 SO 上。
================================================== ====================
在 Python 上?3.5、使用pathlib.Path.mkdir
:
from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)
Run Code Online (Sandbox Code Playgroud)
对于旧版本的 Python,我看到两个质量很好的答案,每个都有一个小缺陷,所以我会给出我的看法:
尝试os.path.exists
,并os.makedirs
为创作考虑。
import os
if not os.path.exists(directory):
os.makedirs(directory)
Run Code Online (Sandbox Code Playgroud)
正如评论和其他地方所指出的,存在竞争条件 - 如果在os.path.exists
和os.makedirs
调用之间创建目录,os.makedirs
则将失败并显示OSError
. 不幸的是,一揽子捕获OSError
并继续并不是万无一失的,因为它会忽略由于其他因素导致的目录创建失败,例如权限不足、磁盘已满等。
一种选择是捕获OSError
并检查嵌入的错误代码(请参阅是否有一种跨平台的方式从 Python 的 OSError 获取信息):
import os, errno
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise
Run Code Online (Sandbox Code Playgroud)
或者,可能有第二个os.path.exists
,但假设另一个人在第一次检查后创建了目录,然后在第二次检查之前将其删除——我们仍然可能被愚弄。
根据应用程序的不同,并发操作的危险可能大于或小于其他因素(例如文件权限)带来的危险。在选择实现之前,开发人员必须更多地了解正在开发的特定应用程序及其预期环境。
现代版本的 Python 通过公开FileExistsError
(在 3.3+ 中)...
try:
os.makedirs("path/to/directory")
except FileExistsError:
# directory already exists
pass
Run Code Online (Sandbox Code Playgroud)
...并允许调用关键字参数os.makedirs
exist_ok
(在 3.2+ 中)。
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.
Run Code Online (Sandbox Code Playgroud)
步骤 1:导入 os.path 模块
\n在运行代码之前导入 os.path 模块。
import os.path\nfrom os import path\n
Run Code Online (Sandbox Code Playgroud)\n步骤2:使用path.exists()函数
\npath.exists()方法用于查找文件是否存在。
path.exists("your_file.txt")\n
Run Code Online (Sandbox Code Playgroud)\n步骤 3:使用 os.path.isfile()
\n我们可以使用 isfile 命令来确定给定的输入是否是文件。
path.isfile(\'your_file.txt\')\n
Run Code Online (Sandbox Code Playgroud)\n步骤 4:使用 os.path.isdir()
\n我们可以使用 os.path.dir() 函数来确定给定的输入是否是目录。
path.isdir(\'myDirectory\')\n
Run Code Online (Sandbox Code Playgroud)\n这是完整的代码
\n import os.path\n from os import path\n \n def main():\n \n print ("File exists:"+str(path.exists(\'your_file.txt\')))\n print ("Directory exists:" + str(path.exists(\'myDirectory\')))\n print("Item is a file: " + str(path.isfile("your_file.txt")))\n print("Item is a directory: " + str(path.isdir("myDirectory")))\n \n if __name__== "__main__":\n main()\n
Run Code Online (Sandbox Code Playgroud)\nPython 3.4 的 pathlibPath.exists()
Python 3.4 及更高版本中包含 Pathlib 模块来处理文件系统路径。Python 使用面向对象的技术检查文件夹是否存在。
\nimport pathlib\nfile = pathlib.Path("your_file.txt")\nif file.exists ():\n print ("File exist")\nelse:\n print ("File not exist")\n
Run Code Online (Sandbox Code Playgroud)\n#You can also check it get help for you
if not os.path.isdir('mydir'):
print('new directry has been created')
os.system('mkdir mydir')
Run Code Online (Sandbox Code Playgroud)
有一个方便的Unipath
模块。
>>> from unipath import Path
>>>
>>> Path('/var/log').exists()
True
>>> Path('/var/log').isdir()
True
Run Code Online (Sandbox Code Playgroud)
您可能需要的其他相关资料:
>>> Path('/var/log/system.log').parent
Path('/var/log')
>>> Path('/var/log/system.log').ancestor(2)
Path('/var')
>>> Path('/var/log/system.log').listdir()
[Path('/var/foo'), Path('/var/bar')]
>>> (Path('/var/log') + '/system.log').isfile()
True
Run Code Online (Sandbox Code Playgroud)
您可以使用 pip 安装它:
$ pip3 install unipath
Run Code Online (Sandbox Code Playgroud)
它类似于内置的pathlib
. 不同之处在于它将每个路径视为一个字符串(Path
是 的子类str
),因此如果某些函数需要一个字符串,您可以轻松地将它传递给一个Path
对象,而无需将其转换为字符串。
例如,这适用于 Django 和settings.py
:
# settings.py
BASE_DIR = Path(__file__).ancestor(2)
STATIC_ROOT = BASE_DIR + '/tmp/static'
Run Code Online (Sandbox Code Playgroud)
两件事情
import os
dirpath = "<dirpath>" # Replace the "<dirpath>" with actual directory path.
if os.path.exists(dirpath):
print("Directory exist")
else: #this is optional if you want to create a directory if doesn't exist.
os.mkdir(dirpath):
print("Directory created")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1032130 次 |
最近记录: |