[英]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: 我对Python的字符串处理相对较新,并且在弄清楚如何解决此问题时遇到了麻烦:我沿着/dir/MAC.timestamp.bin的路线有一条绝对路径,该路径类似于以下内容:
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). 现在,我需要提取MAC(以6个字符开头)。 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? 但是,我不确定100%是否始终都是气密的,还有没有更好的方法来解决这个问题? Any hints are appreciated! 任何提示表示赞赏!
Thank you! 谢谢!
You should use os.path.basename(p)
instead of p.split('/')[-1]
. 您应该使用os.path.basename(p)
而不是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. Python列表可以是带有负数的索引。 with -1
being the last element in the list. -1
是列表中的最后一个元素。
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. 此检查也将受益于检查它是否不包含在您的情况下会产生无效mac
字符。
os.path has functions you will find helpful. os.path具有您会发现有用的功能。 In particular, os.path.basename
and os.path.splitext
. 特别是os.path.basename
和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,)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.