简体   繁体   中英

string: extract first six characters after the last /

I'm relatively new to Python's string handling and have troubles figuring out how to solve this: I have absolute path along the lines of /dir/MAC.timestamp.bin that i'm looping through with something like:

for fh in glob.glob(DATA_FOLDER+"*.bin"):
    retval = database.postdata(fh)

And what I need now, is to extract the MAC (WHICH COMES IN 6 characters). I was thinking of doing something along the lines of

for fh in glob.glob("bin/*.bin"):
    list=fh.split("/")
    lstlen=len(list)
    mac=list[lstlen-1][:6]
    retval = database.postdata(mac,fh)

I'm however not 100% sure if that will be air tight at all times and if there's a better way to handle this? Any hints are appreciated!

Thank you!

You should use os.path.basename(p) instead of p.split('/')[-1] .

For instance:

>>> import os
>>> p = '/dir/MAC.timestamp.bin'
>>> p = os.path.basename(p)
>>> p
'MAC.timestamp.bin'
>>> p[:3]
'MAC'

A more general solution:

>>> import os
>>> p = '/dir/MAC.timestamp.bin'
>>> p = os.path.basename(p)
>>> p.split('.')[0]
'MAC'
>>> s = "this/is/a/test23.123456789.bin"
>>> s.split( "/" )[-1][:6]
'test23'

That should work.

Python lists can be index with negative numbers. with -1 being the last element in the list.

Again, as your question states my solution, and yours, will not be air tight if the incoming data does not conform to your specifications. You will need to add in a check such as the following:

>>> s = "this/is/a/test23.123456789.bin"
>>> last_part = s.split( "/" )[-1].split( "." )
>>> if len( last_part ) != 6:
...  print "Improper file format"
>>> else:
...  print "Correct: %s" % last_format

This check for it would also benefit from checking that it does not contain characters that produce a invalid mac in your case.

os.path has functions you will find helpful. In particular, os.path.basename and os.path.splitext . Maybe try this:

import os.path

for fh in glob.glob("bin/*.bin"):
    filename = os.path.basename(fh)
    mac = os.path.splitext(filename)[0]
    if len(mac) != 6:
        raise(Exception('MAC %r is not six characters long' % (filename,)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM