[Python] Are file handles in Python copied when added to a list? Is there a better way to...

Discussão em 'Python' iniciado por Stack, Fevereiro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on posting a number of images to Bluesky based on conditions. I want to make sure, all files are closed after using them but I'm unclear on how variables behave and what is the best way to handle things.

    My basic structure is like this:

    images = []
    captions = []

    if condition1:
    file1 = open('file1.png', 'rb')
    images.append(file1)
    captions.append('file 1')

    if condition2:
    file2 = open('file2.png', 'rb')
    images.append(file2)
    captions.append('file 2')

    bluesky.send_images('Image post', images, captions)


    Questions:


    • When I append file1, file2, ... to images, are they copied or referenced?


    • Can I just do

      for file in images:
      file.close()


      or what is the best way to close all open files?

    Continue reading...

Compartilhe esta Página