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”子產品,這些功能是:
- os.path.isfile() : To check whether a file exists or not. os.path.isfile() :檢查檔案是否存在。
- os.path.isdir() : To check whether a directory exists or not. os.path.isdir() :檢查目錄是否存在。
- 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 statement
import os
# checking file
if 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 again
if os.path.exists("file.txt"):
print("Now, file exists")
else:
print("File does not exist")
Output 輸出量 File does not exist
Now, file exists
翻譯自: https://www.includehelp.com/python/check-if-a-file-exists-or-not.aspx