open read and close a file in 1 line of code

前端 未结 11 1225

Now I use:

pageHeadSectionFile = open(\'pagehead.section.htm\',\'r\')
output = pageHeadSectionFile.read()
pageHeadSectionFile.close()

But t

相关标签:
11条回答
  • 2020-11-28 05:59

    You don't really have to close it - Python will do it automatically either during garbage collection or at program exit. But as @delnan noted, it's better practice to explicitly close it for various reasons.

    So, what you can do to keep it short, simple and explicit:

    with open('pagehead.section.htm','r') as f:
        output = f.read()
    

    Now it's just two lines and pretty readable, I think.

    0 讨论(0)
  • 2020-11-28 06:01

    Using more_itertools.with_iter, it is possible to open, read, close and assign an equivalent output in one line (excluding the import statement):

    import more_itertools as mit
    
    
    output = "".join(line for line in mit.with_iter(open("pagehead.section.htm", "r")))
    

    Although possible, I would look for another approach other than assigning the contents of a file to a variable, i.e. lazy iteration - this can be done using a traditional with block or in the example above by removing join() and iterating output.

    0 讨论(0)
  • 2020-11-28 06:07

    use ilio: (inline io):

    just one function call instead of file open(), read(), close().

    from ilio import read
    
    content = read('filename')
    
    0 讨论(0)
  • 2020-11-28 06:08

    What you can do is to use the with statement, and write the two steps on one line:

    >>> with open('pagehead.section.htm', 'r') as fin: output = fin.read();
    >>> print(output)
    some content
    

    The with statement will take care to call __exit__ function of the given object even if something bad happened in your code; it's close to the try... finally syntax. For object returned by open, __exit__ corresponds to file closure.

    This statement has been introduced with Python 2.6.

    0 讨论(0)
  • 2020-11-28 06:10

    I frequently do something like this when I need to get a few lines surrounding something I've grepped in a log file:

    $ grep -n "xlrd" requirements.txt | awk -F ":" '{print $1}'
    54
    
    $ python -c "with open('requirements.txt') as file: print ''.join(file.readlines()[52:55])"
    wsgiref==0.1.2
    xlrd==0.9.2
    xlwt==0.7.5
    
    0 讨论(0)
提交回复
热议问题