Hướng dẫn check is folder python
Now available since Python 3.4, import and instantiate a Show
If you're on Python 2, you can backport the pathlib module from pypi,
Now the above is probably the best pragmatic direct answer here, but there's the possibility of a race condition (depending on what you're trying to accomplish), and the fact that the underlying implementation uses a Because Python uses But the rest of this answer attempts to consider these caveats. Longer, much more pedantic answerAvailable since Python 3.4, use the new
So we need to use
Here's the help on
So let's get a file that we know is a file:
By default,
If you dig into the implementation, though, you'll see that
Race Conditions: Why we like tryWe like If you want to check that a file exists before you attempt to read it, and you might be deleting it and then you might be using multiple threads or processes, or another program knows about that file and could delete it - you risk the chance of a race condition if you check it exists, because you are then racing to open it before its condition (its existence) changes. Race conditions are very hard to debug because there's a very small window in which they can cause your program to fail. But if this is your motivation, you can get the value of a Avoiding race conditions without a try statement: suppressPython 3.4 gives us the
Usage:
For earlier Pythons, you could roll your own
Perhaps easier with a try:
Other options that don't meet the ask for "without try":isfile
from the docs:
But if you examine the source of this function, you'll see it actually does use a try statement:
All it's doing is using the given path to see if it can get stats on it, catching If you intend to do something with the file, I would suggest directly attempting it with a try-except to avoid a race condition:
os.access Available for Unix and Windows is
It also suffers from the same race condition problems as
Avoid using Criticism of another answer:Another answer says this about
This answer says it prefers a non-Pythonic, error-prone method, with no justification. It seems to encourage users to use low-level APIs without understanding them. It also creates a context manager which, by unconditionally returning This seems to encourage users to adopt poor practices. |