Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - Determine if folder or file key - Boto

Using boto and Python I am trying to differentiate whether a key is returning a folder of file (I am aware that S3 treats both exactly the same as I am not dealing with a filesystem directly).

What I have at the moment is 2 keys

<Key: my-folder,output/2019/01/28/>
<Key: my-folder,output/2019/01/28/part_1111>

The first being a "Folder" and the second being a "File". What I would like to do is determine whether the key is a "File" but unsure on how to determine this, the obvious is the key not ending in a / but how would I determine that in Python.

If I was iterating over a list() can I turn the key into a string or access the keys attributes?

for obj in srcBucket.list():
   # Get the Key object of the given key, in the bucket
   k = Key(srcBucket, obj.key)
   print(k)
   <Key: my-folder,output/2019/01/28/>
   <Key: my-folder,output/2019/01/28/part_1111>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

S3.Object and S3.ObjectSummary will have the following property:

'ContentType': 'application/x-directory'

if the key is a directory.

for s3_obj_summary in bucket.objects.all():
  if s3_obj_summary.get()['ContentType'] == 'application/x-directory':
    print(str(s3_obj_summary))

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.ObjectSummary.get


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...