Re: Searching for a file

2025-08-10 Thread Peter J. Holzer
On 2025-08-05 22:11:57 -0400, Grant Edwards via Python-list wrote:
> On 2025-08-05, Michael Torrie via Python-list  wrote:
> > On 5/24/25 7:19 PM, Chris Angelico via Python-list wrote:
> >> for dir in dirs:
> >> try: open(dir + "/" + fn).close()
> >> except FileNotFoundError: pass
> >> else: break
> >> 
> >> Is this really all that difficult? Not everything has to be in the stdlib.
> >
> > That would modify atime on unix file systems, no?  Of course most modern
> > file systems on SSDs are mounted with noatime, but still.
> 
> Why not call os.stat() instead of open/close?

The OP used os.path.isfile().

Depending on what you want to achieve, each of three methods might be
appropriate. Calling os.stat() just tells you whether the thing exists
(but of course its return value gives you a lot of extra information).
os.path.isfile() tells you whether it's a file (and it is shorter, too).
open() tells you whether the file is readable.

hjp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | [email protected] |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman3//lists/python-list.python.org


Re: Searching for a file

2025-08-10 Thread Peter J. Holzer
On 2025-08-04 19:22:23 -0600, Michael Torrie via Python-list wrote:
> On 5/24/25 7:19 PM, Chris Angelico via Python-list wrote:
> > for dir in dirs:
> > try: open(dir + "/" + fn).close()
> > except FileNotFoundError: pass
> > else: break
> > 
> > Is this really all that difficult? Not everything has to be in the stdlib.
> 
> That would modify atime on unix file systems, no?

No, you have to actually read the file for that. Just opening is not
enough:

% ls -lu foo
-rw-r--r-- 1 hjp hjp 56 May 28 10:05 foo
% python3
Python 3.12.3 (main, Jun 18 2025, 17:59:45) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> fh = open("foo")
>>> fh.close()
>>>
% ls -lu foo
-rw-r--r-- 1 hjp hjp 56 May 28 10:05 foo

Still unchanged. But:

% python3
Python 3.12.3 (main, Jun 18 2025, 17:59:45) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> fh = open("foo")
>>> s = fh.read()
>>> fh.close()
>>>
% ls -lu foo
-rw-r--r-- 1 hjp hjp 56 Aug  9 20:31 foo

Now the atime is changed.

> Of course most modern file systems on SSDs are mounted with noatime,
> but still.

relatime is probably more common. And definitely more useful.

hjp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | [email protected] |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman3//lists/python-list.python.org