
isdir和isfile
Python provides os.path
module in order to use some file and directory related functions. We can use os.path
in order to check whether a file or directory exists, given path is file or directory, the access time of the directory and path etc.
Python提供了os.path
模块,以使用一些与文件和目录相关的功能。 我们可以使用os.path
来检查文件或目录是否存在,给定的路径是文件或目录,目录和路径的访问时间等。
导入os.path (Import os.path)
Before starting examples we need to import
os.path
module which provides functionalities examined below.
在开始示例之前,我们需要import
os.path
模块,该模块提供以下功能。
import os.path
检查给定的文件或目录是否存在 (Check Given File or Directory Exist)
If we will write or create a file we may need to check whether destination file or directory exists or we want to read a file but we should check before creating exceptions. We can use exists
functions for this situation. In this example we will check wheter /home/ismail
directory exists. We can also provide a file name to check the existence.
如果要写入或创建文件,则可能需要检查目标文件或目录是否存在,或者我们想读取文件,但是在创建异常之前,我们应该进行检查。 在这种情况下,我们可以使用exists
函数。 在此示例中,我们将检查/home/ismail
目录是否存在。 我们还可以提供文件名来检查是否存在。
os.path.exists('/home/ismail')

As we can the given directory exists where the exists
method returns Boolean True
. If the directory do not exists it will return false like below.
我们可以在给定目录存在的地方, exists
方法返回Boolean True
。 如果该目录不存在,它将返回false,如下所示。
os.path.exists('/home/no')

检查给定路径是目录(Check Given Path Is Directory)
After checking the directory or file existence we may want to check whether given path is a directory or a file. We will use isdir
function in order to return Boolean value. If given path is directory isdir
function will return True
if not False
.
检查目录或文件是否存在之后,我们可能要检查给定的路径是目录还是文件。 我们将使用isdir
函数来返回布尔值。 如果给定路径为目录isdir
函数如果不为False
则返回True
。
os.path.isdir('/home/ismail')

检查给定的路径是文件(Check Given Path Is File)
We can check given path is it is a file. As we know there are different type of files and links. This function will also check if given path is a link where points another path. If given path is file isfile
function will return True
.
我们可以检查给定的路径是否是文件。 我们知道文件和链接的类型不同。 此功能还将检查给定的路径是否是指向其他路径的链接。 如果给定路径为file,则isfile
函数将返回True
。
os.path.isfile('/home/ismail')
获取给定的文件或目录访问时间 (Get Given File or Directory Access Time)
We can also get access time of given file or directory. We will use getatime
which is the short form of get access time
. This will return access time as seconds in Unix format.
我们还可以获得给定文件或目录的访问时间。 我们将使用getatime
,它是get access time
的缩写。 这将以Unix格式返回访问时间(以秒为单位)。
os.path.getatime('/home/ismail')

获取给定的文件或目录修改时间(Get Given File or Directory Modification Time)
Another useful function is modification time. We can use getmtime
function which is very similar to the access time. The time is returned as Unix time stamp as seconds.
另一个有用的功能是修改时间。 我们可以使用与访问时间非常相似的getmtime
函数。 时间以Unix时间戳(秒)形式返回。
os.path.getmtime('/home/ismail')

翻译自: https://www.poftut.com/python-os-path-library-using-exist-isdir-isfile-examples/
isdir和isfile