Python tồn tại phương thức [] được sử dụng để kiểm tra xem tệp hoặc thư mục cụ thể có tồn tại hay không. Nó cũng được sử dụng để kiểm tra xem một đường dẫn có đề cập đến bất kỳ mô tả tệp mở nào hay không. Nó trả về giá trị boolean true nếu tệp tồn tại và trả về sai. Nó được sử dụng với mô -đun HĐH và mô -đun phụ OS.Path làm OS.Path.exists [đường dẫn]. method is used to check whether specific file or directory exists or not. It is also used to check if a path refers to any open file descriptor or not. It returns boolean value true if file exists and returns false otherwise. It is used with os module and os.path sub module as os.path.exists[path]. Trong tệp Python này tồn tại hướng dẫn, chúng ta sẽ tìm hiểu cách xác định xem một tệp [hoặc thư mục] có tồn tại bằng Python hay không. Để kiểm tra xem tệp có tồn tại Python hay không, chúng tôi sử dụng kiểm tra python thư viện tích hợp nếu tệp có tồn tại chức năng không. Có nhiều cách khác nhau để xác minh tệp hoặc kiểm tra Python nếu thư mục tồn tại, sử dụng các chức năng như được liệt kê dưới đây. Sử dụng Path.Exists Bạn có thể nhanh chóng kiểm tra xem tệp hoặc thư mục có tồn tại không. Dưới đây là các bước để kiểm tra Python có tồn tại hay không: Bước 1] Nhập mô -đun OS.Path Trước khi bạn chạy mã, điều quan trọng là bạn phải nhập mô -đun OS.Path. Bước 2] Sử dụng Path.Exists [] Funtion Bây giờ, sử dụng hàm path.exists [] để kiểm tra python nếu một tệp tồn tại. Bước 3] Chạy mã được đưa ra dưới đây Đây là mã hoàn chỉnh Trong trường hợp của chúng tôi, chỉ có tệp Guru99.txt được tạo trong thư mục làm việc Output: Tệp tồn tại: Tệp true tồn tại: Thư mục sai tồn tại: Sai Phương thức python isfile [] được sử dụng để tìm xem một đường dẫn nhất định có phải là một tệp thông thường hiện có hay không. Nó trả về một giá trị boolean true nếu đường dẫn cụ thể là một tệp hiện có hoặc nếu không nó sẽ trả về sai. Nó có thể được sử dụng bởi cú pháp: Os.Path.isfile [đường dẫn].Python isfile[] method is used to find whether a given path is an existing regular file or not. It
returns a boolean value true if the specific path is an existing file or else it returns false. It can be used by the syntax : os.path.isfile[path]. Chúng ta có thể sử dụng lệnh isfile để kiểm tra xem một đầu vào đã cho có phải là tệp hay không. Output:Cách kiểm tra xem một tệp có tồn tại trong Python bằng Os.Path.exists []
import os.path
from os import path
path.exists["guru99.txt"]
import os.path
from os import path
def main[]:
print ["File exists:"+str[path.exists['guru99.txt']]]
print ["File exists:" + str[path.exists['career.guru99.txt']]]
print ["directory exists:" + str[path.exists['myDirectory']]]
if __name__== "__main__":
main[]
File exists: False
directory exists: FalsePython isfile []
os.path.isfile[]
import os.path
from os import path
def main[]:
print ["Is it File?" + str[path.isfile['guru99.txt']]]
print ["Is it File?" + str[path.isfile['myDirectory']]]
if __name__== "__main__":
main[]
Nó có phải là tập tin không? Đúng là tập tin? Sai
Is it File? False
os.path.isdir[]
Nếu chúng tôi muốn xác nhận rằng một đường dẫn đã cho đến một thư mục, chúng tôi có thể sử dụng hàm os.path.dir []
import os.path from os import path def main[]: print ["Is it Directory?" + str[path.isdir['guru99.txt']]] print ["Is it Directory?" + str[path.isdir['myDirectory']]] if __name__== "__main__": main[]
Output:
Nó có phải là thư mục không? Sai là thư mục? ĐÚNG VẬY
Is it Directory? True
pathlibpath.exists [] cho Python 3.4
Các phiên bản Python 3.4 trở lên có mô -đun Pathlib để xử lý với đường dẫn hệ thống tệp. Nó sử dụng cách tiếp cận hướng đối tượng để kiểm tra Python nếu thư mục có tồn tại hay không.
import pathlib file = pathlib.Path["guru99.txt"] if file.exists []: print ["File exist"] else: print ["File not exist"]
Output:
Tập tin tồn tại
Hoàn thành mã
Đây là mã hoàn chỉnh
import os from os import path def main[]: # Print the name of the OS print[os.name] #Check for item existence and type print["Item exists:" + str[path.exists["guru99.txt"]]] print["Item is a file: " + str[path.isfile["guru99.txt"]]] print["Item is a directory: " + str[path.isdir["guru99.txt"]]] if __name__ == "__main__": main[]
Output:
Trong trường hợp của chúng tôi, chỉ có tệp Guru99.txt được tạo trong thư mục làm việc
Item is a file: True
Item is a directory: False
Tệp tồn tại: Tệp true tồn tại: Thư mục sai tồn tại: Sai
- Python isfile []
- Phương thức python isfile [] được sử dụng để tìm xem một đường dẫn nhất định có phải là một tệp thông thường hiện có hay không. Nó trả về một giá trị boolean true nếu đường dẫn cụ thể là một tệp hiện có hoặc nếu không nó sẽ trả về sai. Nó có thể được sử dụng bởi cú pháp: Os.Path.isfile [đường dẫn].
- Chúng ta có thể sử dụng lệnh isfile để kiểm tra xem một đầu vào đã cho có phải là tệp hay không.
- Nó có phải là tập tin không? Đúng là tập tin? Sai
Nếu chúng tôi muốn xác nhận rằng một đường dẫn đã cho đến một thư mục, chúng tôi có thể sử dụng hàm os.path.dir []Python Tutorial for Beginners: Learn Programming Basics [PDF]
Làm cách nào để kiểm tra xem một tệp có tồn tại hay không, sử dụng Python, mà không cần sử dụng câu lệnh thử?
Hiện có sẵn kể từ Python 3.4, nhập và khởi tạo đối tượng
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]4 với tên tệp và kiểm tra phương thức
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]5 [lưu ý rằng điều này trả về đúng với các liên kết symlink chỉ vào các tệp thông thường]:
>>> from pathlib import Path
>>> Path['/'].is_file[]
False
>>> Path['/initrd.img'].is_file[]
True
>>> Path['/doesnotexist'].is_file[]
False
Nếu bạn đang sử dụng Python 2, bạn có thể quay lại mô -đun Pathlib từ Pypi,
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]6 hoặc kiểm tra
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]7 từ mô -đun
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]8:
>>> import os
>>> os.path.isfile['/']
False
>>> os.path.isfile['/initrd.img']
True
>>> os.path.isfile['/doesnotexist']
False
Bây giờ những điều trên có lẽ là câu trả lời trực tiếp thực dụng tốt nhất ở đây, nhưng có khả năng một điều kiện chủng tộc [tùy thuộc vào những gì bạn đang cố gắng thực hiện] và thực tế là việc triển khai cơ bản sử dụng
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]9, nhưng Python sử dụng
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]9 ở mọi nơi trong thực hiện.
Bởi vì Python sử dụng
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]9 ở khắp mọi nơi, thực sự không có lý do gì để tránh việc thực hiện sử dụng nó.
Nhưng phần còn lại của câu trả lời này cố gắng xem xét những cảnh báo này.
Dài hơn, câu trả lời giả tạo hơn nhiều
Có sẵn từ Python 3.4, sử dụng đối tượng
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]4 mới trong
import os.path from os import path def main[]: print ["Is it Directory?" + str[path.isdir['guru99.txt']]] print ["Is it Directory?" + str[path.isdir['myDirectory']]] if __name__== "__main__": main[]3. Lưu ý rằng
import os.path from os import path def main[]: print ["Is it Directory?" + str[path.isdir['guru99.txt']]] print ["Is it Directory?" + str[path.isdir['myDirectory']]] if __name__== "__main__": main[]4 không hoàn toàn đúng, bởi vì các thư mục không phải là tệp [ngoại trừ theo nghĩa Unix rằng mọi thứ đều là một tệp].
>>> from pathlib import Path
>>> root = Path['/']
>>> root.exists[]
True
Vì vậy, chúng tôi cần sử dụng
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]5:
path.exists["guru99.txt"]0
Đây là sự giúp đỡ trên
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]5:
path.exists["guru99.txt"]1
Vì vậy, chúng ta hãy lấy một tệp mà chúng ta biết là một tệp:
path.exists["guru99.txt"]2
Theo mặc định,
import os.path from os import path def main[]: print ["Is it Directory?" + str[path.isdir['guru99.txt']]] print ["Is it Directory?" + str[path.isdir['myDirectory']]] if __name__== "__main__": main[]7 xóa tệp khi đóng [và sẽ tự động đóng khi không có thêm tài liệu tham khảo nào tồn tại].
path.exists["guru99.txt"]3
Tuy nhiên, nếu bạn đào sâu vào việc thực hiện, bạn sẽ thấy rằng
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]5 sử dụng
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]9:
path.exists["guru99.txt"]4
Điều kiện cuộc đua: Tại sao chúng tôi thích thử
Chúng tôi thích
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]9 vì nó tránh được điều kiện chủng tộc. Với
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]9, bạn chỉ cần cố gắng đọc tệp của mình, hy vọng nó sẽ ở đó, và nếu không, bạn sẽ nắm bắt được ngoại lệ và thực hiện bất kỳ hành vi dự phòng nào có ý nghĩa.
Nếu bạn muốn kiểm tra xem một tệp có tồn tại không trước khi bạn cố đọc nó và bạn có thể xóa nó và sau đó bạn có thể sử dụng nhiều luồng hoặc quy trình, hoặc một chương trình khác biết về tệp đó và có thể xóa nó - bạn có nguy cơ Một điều kiện cuộc đua nếu bạn kiểm tra nó tồn tại, bởi vì sau đó bạn đang chạy đua để mở nó trước khi điều kiện [sự tồn tại của nó] thay đổi.race condition if you check it exists, because you are then racing to open it before its condition [its existence] changes.
Điều kiện chủng tộc rất khó để gỡ lỗi vì có một cửa sổ rất nhỏ trong đó chúng có thể khiến chương trình của bạn thất bại.
Nhưng nếu đây là động lực của bạn, bạn có thể nhận được giá trị của câu lệnh
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]9 bằng cách sử dụng trình quản lý bối cảnh
import pathlib file = pathlib.Path["guru99.txt"] if file.exists []: print ["File exist"] else: print ["File not exist"]3.
Tránh các điều kiện chủng tộc mà không có tuyên bố thử: import pathlib
file = pathlib.Path["guru99.txt"]
if file.exists []:
print ["File exist"]
else:
print ["File not exist"]
3
Python 3.4 cung cấp cho chúng tôi Trình quản lý bối cảnh
import pathlib file = pathlib.Path["guru99.txt"] if file.exists []: print ["File exist"] else: print ["File not exist"]3 [trước đây là Trình quản lý bối cảnh
import pathlib file = pathlib.Path["guru99.txt"] if file.exists []: print ["File exist"] else: print ["File not exist"]6], điều này chính xác về mặt ngữ nghĩa trong ít dòng hơn, trong khi [ít nhất là hời hợt] đáp ứng yêu cầu ban đầu để tránh tuyên bố
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]9:
path.exists["guru99.txt"]5
Usage:
path.exists["guru99.txt"]6
Đối với Pythons trước đó, bạn có thể tự cuộn
import pathlib file = pathlib.Path["guru99.txt"] if file.exists []: print ["File exist"] else: print ["File not exist"]3 của riêng mình, nhưng không có
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]9 sẽ có nhiều dòng hơn. Tôi tin rằng đây thực sự là câu trả lời duy nhất không sử dụng
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]9 ở bất kỳ cấp độ nào trong Python có thể được áp dụng cho trước Python 3.4 vì nó sử dụng trình quản lý bối cảnh thay thế: thay vào đó:this actually is the only answer that doesn't use
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]9 at any level in the Python that can be applied to prior to Python 3.4 because it uses a context manager instead:
path.exists["guru99.txt"]7
Có lẽ dễ dàng hơn với một thử:
path.exists["guru99.txt"]8
Các tùy chọn khác không đáp ứng yêu cầu "mà không cần thử":
isfile
path.exists["guru99.txt"]9
Từ các tài liệu:
import os from os import path def main[]: # Print the name of the OS print[os.name] #Check for item existence and type print["Item exists:" + str[path.exists["guru99.txt"]]] print["Item is a file: " + str[path.isfile["guru99.txt"]]] print["Item is a directory: " + str[path.isdir["guru99.txt"]]] if __name__ == "__main__": main[]1Trả về đúng nếu đường dẫn là một tệp thông thường hiện có. Điều này theo các liên kết tượng trưng, vì vậy cả
import os from os import path def main[]: # Print the name of the OS print[os.name] #Check for item existence and type print["Item exists:" + str[path.exists["guru99.txt"]]] print["Item is a file: " + str[path.isfile["guru99.txt"]]] print["Item is a directory: " + str[path.isdir["guru99.txt"]]] if __name__ == "__main__": main[]2 vàimport os from os import path def main[]: # Print the name of the OS print[os.name] #Check for item existence and type print["Item exists:" + str[path.exists["guru99.txt"]]] print["Item is a file: " + str[path.isfile["guru99.txt"]]] print["Item is a directory: " + str[path.isdir["guru99.txt"]]] if __name__ == "__main__": main[]3 đều có thể đúng cho cùng một đường dẫn.
Nhưng nếu bạn kiểm tra nguồn của chức năng này, bạn sẽ thấy nó thực sự sử dụng câu lệnh thử:
import os.path from os import path def main[]: print ["File exists:"+str[path.exists['guru99.txt']]] print ["File exists:" + str[path.exists['career.guru99.txt']]] print ["directory exists:" + str[path.exists['myDirectory']]] if __name__== "__main__": main[]0
import os.path from os import path def main[]: print ["File exists:"+str[path.exists['guru99.txt']]] print ["File exists:" + str[path.exists['career.guru99.txt']]] print ["directory exists:" + str[path.exists['myDirectory']]] if __name__== "__main__": main[]1
Tất cả những gì nó đang làm là sử dụng đường dẫn đã cho để xem liệu nó có thể nhận được số liệu thống kê trên đó không, bắt
import os from os import path def main[]: # Print the name of the OS print[os.name] #Check for item existence and type print["Item exists:" + str[path.exists["guru99.txt"]]] print["Item is a file: " + str[path.isfile["guru99.txt"]]] print["Item is a directory: " + str[path.isdir["guru99.txt"]]] if __name__ == "__main__": main[]4 và sau đó kiểm tra xem đó có phải là tệp không nếu nó không tăng ngoại lệ.
Nếu bạn có ý định làm điều gì đó với tệp, tôi sẽ đề nghị trực tiếp thử nó với một thử nghiệm để tránh điều kiện cuộc đua:
import os.path from os import path def main[]: print ["File exists:"+str[path.exists['guru99.txt']]] print ["File exists:" + str[path.exists['career.guru99.txt']]] print ["directory exists:" + str[path.exists['myDirectory']]] if __name__== "__main__": main[]2
os.access
Có sẵn cho Unix và Windows là
import os from os import path def main[]: # Print the name of the OS print[os.name] #Check for item existence and type print["Item exists:" + str[path.exists["guru99.txt"]]] print["Item is a file: " + str[path.isfile["guru99.txt"]]] print["Item is a directory: " + str[path.isdir["guru99.txt"]]] if __name__ == "__main__": main[]5, nhưng để sử dụng, bạn phải vượt qua cờ và nó không phân biệt giữa các tệp và thư mục. Điều này được sử dụng nhiều hơn để kiểm tra xem người dùng gọi thực sự có quyền truy cập trong môi trường đặc quyền nâng cao không:
import os.path from os import path def main[]: print ["File exists:"+str[path.exists['guru99.txt']]] print ["File exists:" + str[path.exists['career.guru99.txt']]] print ["directory exists:" + str[path.exists['myDirectory']]] if __name__== "__main__": main[]3
Nó cũng bị các vấn đề tình trạng chủng tộc tương tự như
import os.path from os import path def main[]: print ["Is it File?" + str[path.isfile['guru99.txt']]] print ["Is it File?" + str[path.isfile['myDirectory']]] if __name__== "__main__": main[]7. Từ các tài liệu:
Lưu ý: Sử dụng Access [] để kiểm tra xem người dùng có được ủy quyền, ví dụ: Mở một tệp trước khi thực sự thực hiện bằng cách sử dụng Open [] tạo lỗ bảo mật, bởi vì người dùng có thể khai thác khoảng thời gian ngắn giữa việc kiểm tra và mở tệp để thao tác nó. Nó thích hợp hơn để sử dụng các kỹ thuật EAFP. Ví dụ:
import os.path from os import path def main[]: print ["File exists:"+str[path.exists['guru99.txt']]] print ["File exists:" + str[path.exists['career.guru99.txt']]] print ["directory exists:" + str[path.exists['myDirectory']]] if __name__== "__main__": main[]4được viết tốt hơn như:
import os.path from os import path def main[]: print ["File exists:"+str[path.exists['guru99.txt']]] print ["File exists:" + str[path.exists['career.guru99.txt']]] print ["directory exists:" + str[path.exists['myDirectory']]] if __name__== "__main__": main[]5
Tránh sử dụng
import os from os import path def main[]: # Print the name of the OS print[os.name] #Check for item existence and type print["Item exists:" + str[path.exists["guru99.txt"]]] print["Item is a file: " + str[path.isfile["guru99.txt"]]] print["Item is a directory: " + str[path.isdir["guru99.txt"]]] if __name__ == "__main__": main[]5. Đây là một chức năng cấp thấp có nhiều cơ hội cho lỗi người dùng hơn các đối tượng và chức năng cấp cao hơn được thảo luận ở trên.
Phê bình về một câu trả lời khác:
Một câu trả lời khác nói điều này về
import os from os import path def main[]: # Print the name of the OS print[os.name] #Check for item existence and type print["Item exists:" + str[path.exists["guru99.txt"]]] print["Item is a file: " + str[path.isfile["guru99.txt"]]] print["Item is a directory: " + str[path.isdir["guru99.txt"]]] if __name__ == "__main__": main[]5:
Tôi thích cái này vì dưới mui xe, nó gọi API gốc [thông qua "$ {python_src_dir} /modules/posixmodule.c"], nhưng nó cũng mở một cổng cho các lỗi người dùng có thể và nó không phải là pythonic như các biến thể khác :
Câu trả lời này cho biết nó thích một phương pháp không giống, dễ bị lỗi, không có lý do. Nó dường như khuyến khích người dùng sử dụng API cấp thấp mà không hiểu chúng.
Nó cũng tạo ra một trình quản lý bối cảnh, bằng cách trả lại vô điều kiện
import os.path from os import path def main[]: print ["File exists:"+str[path.exists['guru99.txt']]] print ["File exists:" + str[path.exists['career.guru99.txt']]] print ["directory exists:" + str[path.exists['myDirectory']]] if __name__== "__main__": main[]7, cho phép tất cả các trường hợp ngoại lệ [bao gồm
>>> from pathlib import Path
>>> Path['/'].is_file[]
False
>>> Path['/initrd.img'].is_file[]
True
>>> Path['/doesnotexist'].is_file[]
False
0 và >>> from pathlib import Path
>>> Path['/'].is_file[]
False
>>> Path['/initrd.img'].is_file[]
True
>>> Path['/doesnotexist'].is_file[]
False
1!] Để vượt qua âm thầm, đó là một cách tốt để che giấu lỗi.Điều này dường như khuyến khích người dùng áp dụng các hoạt động kém.