[Tutor] Regex for Filesystem path
Cameron Simpson
cs at cskk.id.au
Tue Nov 6 14:47:33 EST 2018
On 06Nov2018 18:10, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
>On 06/11/2018 13:13, Asad wrote:
>
>> Can you provide some advice and code for the following problem :
>
>The first thing is to go read the documentation for the os.path module.
>It is designed for reliable path manipulation.
>
>> /a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log
>>
>> f3 = open ( r"/a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log", 'r' )
>> st1 = f3.readlines ()
>
>You hardly ever need readlines() any more, just iterate
>over the file, its much easier.
>
>> for j in range ( len ( st1 ) ):
>
>for line in f3:
Not to mention cheaper in memory usage.
[...snip...]
>> a = mo.group() ## 123456/789
>> ===================================================================
>> How to do I traverse to the required directory which is
>> /a/b/c/d/test/123456/789 ?
>
>You can use relative paths in os.chdir.
>So a payth of '..' will be one level up from the current
>directory. Of course you need to chdir to that directory first
>but os.path will tell you the dir you need.
It is better to just construct the required path. Chdir there requires a
chdir back, and chdir affects all the relative paths your programme may
be using.
I'd use os.path.dirname to get '/a/b/c/d/test' and then just append to
it with os.path.join to contruct each directory path.
[...]
>But I'm guessing that's too obvious so the path may vary?
>> 1) First I need to extract /a/b/c/d/test/ from
>> /a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log ?
Use os.path.dirname:
# up the top
from os.path import dirname, join
# later
testdir = dirname(logfile_path)
>get the dir then chdir to .. from there.
>
>> 2) Then add 123456/789 and create directory location as
>> /a/b/c/d/test/123456/789
>
>Simple string manipulation or use the os.path functions.
Eg dirpath = join(testdir, '123456/789')
>> 3) cd /a/b/c/d/test/123456/789
>
>os.chdir()
I still recommend avoiding this. Just construct the full path to what
you need.
>> 4) look for the latest file in the directory /a/b/c/d/test/123456/789
>
>Slightly more complex, you need the creation timestamp.
>You can find that with os.path.getctime() (or several
>other options, eg os.stat)
Do not use ctime, it is _not_ "creation" time. It is "last change to
inode" time. It _starts_ as creation time, but a chmod or even a
link/unlink can change it: anything that changes the metadata.
Generally people want mtime (last nmodified time), which is the last
time the file data got changed. It is more meaningful.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list