open read and close a file in 1 line of code

前端 未结 11 1384

Now I use:

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

But t

11条回答
  •  不知归路
    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
    

提交回复
热议问题