Overhead of going around a file object instead of a file name?

I have a method that determines which file it should open based on input, open the file, and then return the file.

def find_and_open(search_term):
    # ... logic to find file
    return open(filename, 'r')

I like this way because it hides most of the implementation from the caller. You give him your criteria, he spits out a file object. Why bother with string paths if you're going to open it anyway?

However, in other Python projects, I tend to see that such a method returns the string of the path to the file, not the file itself. Then the file opens at the last minute, reads / edits and closes.

My questions:

  • In terms of performance, is there a move of file objects with a lot of overhead? I believe that a link is a link, regardless of what it points to, but is it possible something happens in the interpreter, which refers to the String link rather than the file link?

  • From a purely “Pythonic” point of view, does it make sense to return a file object or a String path (and then open the file as late as possible)?

+4
source share
1 answer
  • Performance is unlikely to be a problem. Reading and writing to disk is several orders of magnitude slower than reading from RAM, so passing the pointer around is unlikely to be a performance bottleneck. 1
  • From python docs :

    with . , , . , try - finally...

, with, , yield. pythonic, .

, .      , .

pathlib.

+3

All Articles