Python判斷檔案和資料夾是否存在的方法

2021-07-09 07:33:13 字數 1836 閱讀 9671

一、python判斷檔案和資料夾是否存在、建立資料夾

複製**

**如下:

>>> import os

>>>

os.path.exists('d:/assist')

true

>>> os.path.exists('d:/assist/getteacherlist.py')

true

>>>

os.path.isfile('d:/assist')

false

>>> os.path.isfile('d:/assist/getteacherlist.py')

true

>>>

os.makedirs('d:/assist/set')

>>> os.path.exists('d:/assist/set')

true

>>> tobecheckdir = r'/home/tim/workspace'

>>>

os.path.isdir(tobecheckdir)

true

>>>

二、python檢查檔案是否存在,以及路徑是否為檔案

在寫檔案之前通常需要檢查檔案路徑是否可寫:

複製**

**如下:

from os import path, access, r_ok  # w_ok for write permission.

path='./file.txt'

if path.exists(path) and path.isfile(path) and access(path, r_ok):

print "file exists and is readable"

else:

print "either file is missing or is not readable"

你也可以通過下面的方式實現:

複製**

**如下:

def file_exists(filename):

try:

with open(filename) as f:

return true

except ioerror:

return false

三、os.path.lexist

還有os.path.lexists(path)

對broken的link file也返回true.

四、python ftp判斷資料夾是否存在

python怎樣判斷資料夾是否存在?廣大網友給出了答案:

使用ftp庫就可以了,下面是python核心程式設計上的例子:

複製**

**如下:

>>> from ftplib import ftp

>>> f = ftp('ftp.python.org')

>>> f.login('anonymous', '[email protected]')

>>> f.dir()

dir結果中無此檔案,就是不存在。

或者如下:

複製**

**如下:

try:

f.retrbinary('retr %s' % file,open(file, 'wb').write)

except ftplib.error_perm:

print 'error: cannot read file "%s"' % file 40 os.unlink(file)

不能讀此檔案,也視為不存在。

Linux shell判斷檔案和資料夾是否存在

shell判斷檔案,目錄是否存在或者具有許可權 這裡的 x 引數判斷 mypath是否存在並且是否具有可執行許可權 if x mypath then mkdir mypath fi www.2cto.com 這裡的 d 引數判斷 mypath是否存在 if d mypath then mkdir m...

Linux shell判斷檔案和資料夾是否存在

這裡的 x 引數判斷 mypath是否存在並且是否具有可執行許可權 if x mypath then mkdir mypath fi 這裡的 d 引數判斷 mypath是否存在 if d mypath then mkdir mypath fi 這裡的 f引數判斷 myfile是否存在 if f my...

python判斷檔案和資料夾是否存在 建立資料夾

python中對檔案 資料夾的操作需要涉及到os模組和shutil模組。1 os.mknod test.txt 建立空檔案 2 open test.txt w 直接開啟乙個檔案,如果檔案不存在則建立檔案 os.mkdir file 建立目錄 shutil.copyfile oldfile newfi...