In Python, how can I open a file and read it on one line, and still be able to close the file afterwards?

前端 未结 7 2133
面向向阳花
面向向阳花 2021-02-10 07:26

While working through this exercise I ran into a problem.

from sys import argv
from os.path import exists

script, from_file, to_file = argv
print \"Copying from         


        
7条回答
  •  野性不改
    2021-02-10 07:59

    The preferred way to work with resources in python is to use context managers:

     with open(infile) as fp:
        indata = fp.read()
    

    The with statement takes care of closing the resource and cleaning up.

    You could write that on one line if you want:

     with open(infile) as fp: indata = fp.read()
    

    however, this is considered bad style in python.

    You can also open multiple files in a with block:

    with open(input, 'r') as infile, open(output, 'w') as outfile:
        # use infile, outfile
    

    Funny enough, I asked exactly the same question back when I started learning python.

提交回复
热议问题