当前位置:首页 » 编程语言 » python目录存在

python目录存在

发布时间: 2024-12-25 20:18:51

python如何判断一个目录下是否存在某个文件

1.使用os模块

  • 用os模块中os.path.exists()方法检测是否存在test_file.txt文件

importos
os.path.exists(test_file.txt)
#True
os.path.exists(no_exist_file.txt)
#False

2.使用Try命令

  • 使用open()方法,如果要打开的文件不存在,就回跑出异常,用try()方法捕获异常。

try:
f=open(test_file.txt)
f.close()
exceptIOError:
print"fileisnotaccessible"

3. 使用pathlib

  • 检查路径是否存在

path=pathlib.Path("path/file")
path.exist()
  • 检查路径是否是文件

path=pathlib.Path("path/file")
path.is_file()

㈡ python如何判断一个目录下是否存在某个文件谢啦!

使用os.path.exists()方法可以直接判断文件是否存在。
代码如下:
>>> import os
>>> os.path.exists(r'C:\1.TXT')
False
>>>
如果存在返回值为True如果不存在则返回False。很方便
希望对你有所帮助~~

㈢ python 当文件目录不存在时,如何自动创建

Python对文件的操作算是方便的,只 需要调用os模块,使用相关函数即可实现目录的创建。主要涉及三个函数:

1、os.path.exists(path)判断一个目录是否存在

2、os.makedirs(path)多层创建目录

3、os.mkdir(path)创建目录

defmkdir(path):
#引入模块
importos

#去除首位空格
path=path.strip()

#去除尾部符号
path=path.rstrip("\")

#判断路径是否存在
#存在True
#不存在False
isExists=os.path.exists(path)

#判断结果
ifnotisExists:
#如果不存在则创建目录
#创建目录操作函数
os.makedirs(path)
print(path+'创建成功')
returnTrue
else:
#如果目录存在则不创建,并提示目录已存在
print(path+'目录已存在')
returnFalse

#定义要创建的目录
mkpath="d:\qttc\web\"
#调用函数
mkdir(mkpath)

注意:os.mkdir(path)函数和多层创建目录函数os.makedirs(path)的区别。主要是当父目录不存在的时候os.mkdir(path)不会创建,而os.makedirs(path)会创建父目录。

热点内容
王者荣耀安卓一区是什么 发布:2025-09-15 22:07:26 浏览:387
云架构数据库 发布:2025-09-15 22:01:01 浏览:335
广州数控车床编程视频 发布:2025-09-15 21:59:43 浏览:395
服务器ip修改后oracle服务器 发布:2025-09-15 21:58:08 浏览:402
禁止进程被访问 发布:2025-09-15 21:55:00 浏览:255
编译udf提示无stdioh 发布:2025-09-15 21:39:25 浏览:22
压缩比数据 发布:2025-09-15 21:29:52 浏览:199
android刷ios 发布:2025-09-15 21:22:18 浏览:35
买服务器如何砍价 发布:2025-09-15 21:04:27 浏览:822
我的世界直连服务器的区别 发布:2025-09-15 20:59:12 浏览:64