1

I'm trying to print a list or dict of file names into a text file. it's currently only returning the first item on the list. the items are fetched from s3 Aws.I'm using Python 2.6

for obj in bucket.objects.filter(Prefix=prefix):
      s = obj.key
      with open('test.txt', 'w') as f:
          f.write(s)
4
  • 1
    So for every item, you create a new file test.txt and write that specific object to the file? Commented Dec 19, 2017 at 15:16
  • In fact it is returning the last item. Commented Dec 19, 2017 at 15:16
  • I'm trying to return ALL the items into the list. Commented Dec 19, 2017 at 15:18
  • exaclty, and I explain why it does not work with your implementation... Commented Dec 19, 2017 at 15:18

2 Answers 2

2

The problem here is that for every item, you create a new file (in case the file already exists, you remove the content so to speak), and then write s to it.

So you should swap the order of things here:

with open('test.txt', 'w') as f:  # first open the file
    for obj in bucket.objects.filter(Prefix=prefix):  # then iterate
        f.write(obj.key)

So we keep the file handle open, and each item will be written. A potential problem is that you will not write a new line after you written the key of an object. We can do this by writing a new line as well:

with open('test.txt', 'w') as f:
    for obj in bucket.objects.filter(Prefix=prefix):
        f.write(obj.key)
        f.write('\n')
Sign up to request clarification or add additional context in comments.

3 Comments

can you make it so that the format is not. 12345 and instead 1,2,3,4,5 and/or newline
@user3821872: the formatis is not what? The second implementation writes new lines between the keys...
fantastic THANKS A BUNCH
1

whenever you open a file for writing, the previous content is erased and new text is written. So in this case you are erasing whatever you wrote to the file in the next iteration. you can do it in this way or open the file in "append" mode and continue with what you have written.

f= open("test.txt", "w")
for obj in bucket.objects.filter(Prefix=prefix):
      s = obj.key
      f.write(s)
      f.write('\n)
f.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.