open read and close a file in 1 line of code

前端 未结 11 1224

Now I use:

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

But t

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

    Python Standard Library Pathlib module does what you looking for:

    Path('pagehead.section.htm').read_text()
    

    Don't forget to import Path:

    jsk@dev1:~$ python3
    Python 3.5.2 (default, Sep 10 2016, 08:21:44)
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from pathlib import Path
    >>> (Path("/etc") / "hostname").read_text()
    'dev1.example\n'
    

    On Python 27 install backported pathlib or pathlib2

    0 讨论(0)
  • 2020-11-28 05:44

    Using CPython, your file will be closed immediately after the line is executed, because the file object is immediately garbage collected. There are two drawbacks, though:

    1. In Python implementations different from CPython, the file often isn't immediately closed, but rather at a later time, beyond your control.

    2. In Python 3.2 or above, this will throw a ResourceWarning, if enabled.

    Better to invest one additional line:

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

    This will ensure that the file is correctly closed under all circumstances.

    0 讨论(0)
  • 2020-11-28 05:46

    If you want that warm and fuzzy feeling just go with with.

    For python 3.6 I ran these two programs under a fresh start of IDLE, giving runtimes of:

    0.002000093460083008  Test A
    0.0020003318786621094 Test B: with guaranteed close
    

    So not much of a difference.

    #--------*---------*---------*---------*---------*---------*---------*---------*
    # Desc: Test A for reading a text file line-by-line into a list
    #--------*---------*---------*---------*---------*---------*---------*---------*
    
    import sys
    import time
    
    #                                  # MAINLINE
    if __name__ == '__main__':
        print("OK, starting program...")
    
        inTextFile = '/Users/Mike/Desktop/garbage.txt'
    
    #                                  # Test: A: no 'with;
        c=[]
        start_time = time.time()
        c = open(inTextFile).read().splitlines()
        print("--- %s seconds ---" % (time.time() - start_time))
    
        print("OK, program execution has ended.")
        sys.exit()                     # END MAINLINE
    

    OUTPUT:

    OK, starting program...
    --- 0.002000093460083008 seconds ---
    OK, program execution has ended.
    
    #--------*---------*---------*---------*---------*---------*---------*---------*
    # Desc: Test B for reading a text file line-by-line into a list
    #--------*---------*---------*---------*---------*---------*---------*---------*
    
    import sys
    import time
    
    #                                  # MAINLINE
    if __name__ == '__main__':
        print("OK, starting program...")
    
        inTextFile = '/Users/Mike/Desktop/garbage.txt'
    
    #                                  # Test: B: using 'with'
        c=[]
        start_time = time.time()
        with open(inTextFile) as D: c = D.read().splitlines()
        print("--- %s seconds ---" % (time.time() - start_time))
    
        print("OK, program execution has ended.")
        sys.exit()                     # END MAINLINE
    

    OUTPUT:

    OK, starting program...
    --- 0.0020003318786621094 seconds ---
    OK, program execution has ended.
    
    0 讨论(0)
  • 2020-11-28 05:50
    with open('pagehead.section.htm')as f:contents=f.read()
    
    0 讨论(0)
  • 2020-11-28 05:52

    I think the most natural way for achieving this is to define a function.

    def read(filename):
        f = open(filename, 'r')
        output = f.read()
        f.close()
        return output
    

    Then you can do the following:

    output = read('pagehead.section.htm')
    
    0 讨论(0)
  • 2020-11-28 05:54

    No need to import any special libraries to do this.

    Use normal syntax and it will open the file for reading then close it.

    with open("/etc/hostname","r") as f: print f.read() 
    

    or

    with open("/etc/hosts","r") as f: x = f.read().splitlines()
    

    which gives you an array x containing the lines, and can be printed like so:

    for line in x: print line
    

    These one-liners are very helpful for maintenance - basically self-documenting.

    0 讨论(0)
提交回复
热议问题