博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python | 检查文件是否存在?
阅读量:2530 次
发布时间:2019-05-11

本文共 1480 字,大约阅读时间需要 4 分钟。

The task is to check whether a file exists or not?

任务是检查文件是否存在

Before continuing to the tutorial, please note that – there are some of the separate functions which are used to check whether a file or directory exists or not. So you have to make sure what you want to check a file or a directory.

在继续学习本教程之前,请注意–有一些单独的函数用于检查文件或目录是否存在 。 因此,您必须确定要检查文件或目录的内容。

To use the functions, we have to import the "os" module, the functions are:

要使用这些功能,我们必须导入“ os”模块,这些功能是:

  1. os.path.isfile(): To check whether a file exists or not.

    os.path.isfile() :检查文件是否存在。

  2. os.path.isdir(): To check whether a directory exists or not.

    os.path.isdir() :检查目录是否存在。

  3. os.path.exists(): To check for both either a file or a directory.

    os.path.exists() :检查文件还是目录。

So, if you are not sure about the file or directory, I would recommend using "os.path.exists()" function to avoid the error.

因此,如果不确定文件或目录,建议使用“ os.path.exists()”函数来避免该错误。

Example:

例:

In this example, we are checking a file "file.txt" and if it does not exist, we will create and close the file and then again check for the same file.

在此示例中,我们正在检查文件“ file.txt” ,如果该文件不存在,则将创建并关闭该文件,然后再次检查同一文件。

# import statementimport os# checking fileif not(os.path.exists("file.txt")):	print("File does not exist")	# creating & closing file 	fo = open("file.txt","wt")	fo.close();else:	print("File exists")# checking againif os.path.exists("file.txt"):	print("Now, file exists")else:	print("File does not exist")

Output

输出量

File does not existNow, file exists

翻译自:

转载地址:http://kzozd.baihongyu.com/

你可能感兴趣的文章
4.1 分解条件式
查看>>
Equivalent Strings
查看>>
flume handler
查看>>
收藏其他博客园主写的代码,学习加自用。先表示感谢!!!
查看>>
H5 表单标签
查看>>
su 与 su - 区别
查看>>
C语言编程-9_4 字符统计
查看>>
在webconfig中写好连接后,在程序中如何调用?
查看>>
限制用户不能删除SharePoint列表中的条目(项目)
查看>>
【Linux网络编程】使用GDB调试程序
查看>>
feign调用spring clound eureka 注册中心服务
查看>>
ZT:Linux上安装JDK,最准确
查看>>
LimeJS指南3
查看>>
关于C++ const成员的一些细节
查看>>
《代码大全》学习摘要(五)软件构建中的设计(下)
查看>>
C#检测驱动是否安装的问题
查看>>
web-4. 装饰页面的图像
查看>>
微信测试账户
查看>>
Android ListView上拉获取下一页
查看>>
算法练习题
查看>>