open read and close a file in 1 line of code

前端 未结 11 1377

Now I use:

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

But t

11条回答
  •  盖世英雄少女心
    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.

提交回复
热议问题